Thoughts on Instant Loading in WordPress

on in AJAX and Fetching Data
Last modified on

If you are familiar with the instant loading concept, you’ll know it’s about faster subsequent page loads by prefetching hovered links.

There are several solutions – both libraries and custom code – helping to achieve this, but they all have their downsides.

Note: Instant Loading has been implemented in WordPress Lightouse plugin 3.3.

Libraries

Google’s Quicklink
Link

As their description says “a drop-in solution for sites to prefetch links based on what is in the user’s viewport”, imagine this library running on a photo gallery site, where users scroll and hover the images but don’t click. It’s a lot of wasted bandwidth and server resources.

instant.page
Link

This script works by prefetching the page before a user clicks on a link. When a user has hovered for 65 ms there is one chance out of two that they will click on that link, so instant.page starts preloading at this moment, leaving on average over 300 ms for the page to preload.

This is a good library, but you’ll have to host it yourself and configure the data attributes. Speed improvements will be observed over time, so make sure you track and measure your pagespeed in Google Analytics or SpeedFactor.

There are more libraries out there, all variations of the libraries above, some of them using modern techniques, IntesectionObserver, polyfills, different delays and implementations.

All of these scripts, provided either as a WordPress plugin or as custom code, load the library from a CDN. Lots of privacy extensions (Chrome or Firefox) treat these scripts as privacy-invasive and they block the script, so your speed improvements are back to square one.

Custom Code

Here are some custom code solutions to implement in your WordPress theme or plugin. Note that some of them are outdated or don’t use best practices or modern code, but they provide a very good starting point.

Custom Code #1

This one is a really simple one, using vanilla JavaScript, but no throttle/delay. Also, it only prerenders resources.

var links = document.querySelectorAll('a');

[].forEach.call(links, function(link) {
    link.addEventListener("mouseenter", function() {
        var newPreLoadLink = document.createElement("link");
        newPreLoadLink.rel = "prerender";
        newPreLoadLink.href = link.href;

        document.head.appendChild(newPreLoadLink);
    })
});

Source

Custom Code #2

Check the source on this as there’s more interesting reading and options.

document.querySelectorAll('a').forEach(link => {    
    link.addEventListener('mouseover', (e) => {
        let href = link.getAttribute('href');
        let prerenderLink = document.createElement("link");
        prerenderLink.setAttribute("rel", "prerender");
        prerenderLink.setAttribute("rel", "prefetch");
        prerenderLink.setAttribute("href", href);

        document.head.appendChild(prerenderLink);
    });
});

Source

Related posts