Skip to content
This repository has been archived by the owner on Jan 11, 2023. It is now read-only.

Export prefetch #61

Merged
merged 1 commit into from
Jan 3, 2018
Merged

Export prefetch #61

merged 1 commit into from
Jan 3, 2018

Conversation

EmilTholin
Copy link
Member

Thank you for your hard work on Sapper. It is nothing short of amazing!

One of my favorite features is the prefetching that is done when hovering over an anchor tag with rel=prefetch. It is super awesome in 95% of use cases, but maybe it could also be useful to export prefetch so that it can be used imperatively?

This opens up for cool user land possibilities, like e.g. prefetching a page when an anchor tag leading to that page is scrolled into the viewport:

<!-- MyAnchor.html  -->
<a href={{href}} ref:anchor>
    <slot></slot>
</a>

<script>
    import { prefetch } from 'sapper/runtime.js';
    const ioIsSupported = 
        typeof window !== 'undefined' && 'IntersectionObserver' in window;

    export default {
        oncreate() {
            if (!ioIsSupported) {
                return;
            }

            const { anchor } = this.refs;
            const { href } = anchor;
            let io = this.io = new IntersectionObserver(entries => {
                entries.forEach(entry => {
                    if (anchor === entry.target && entry.intersectionRatio > 0) {
                        io.unobserve(anchor);
                        io.disconnect();
                        this.io = null;
                        prefetch(href);
                    }
                });
            });

            io.observe(anchor);
        },

        ondestroy() {
            if (this.io) {
                const { anchor } = this.refs;
                this.io.unobserve(anchor);
                this.io.disconnect();
            }
        }
    }
</script>

prefetch_io

I totally understand if you think this is outside the scope of Sapper, but maybe we could discuss it!

@Rich-Harris Rich-Harris merged commit e87ac1f into sveltejs:master Jan 3, 2018
@Rich-Harris
Copy link
Member

Thanks!

I'm afraid you're wrong, totally wrong — I think it's well inside the scope of Sapper 😀 In fact I meant to get round to it myself, but now you've saved me the trouble, so thank you! I took the liberty of adding a test, and released it as 0.3.2.

@EmilTholin EmilTholin deleted the imperative_prefetch branch January 3, 2018 18:50
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants