Search code examples
javascriptwordpresslazy-loadingpagespeed

How to force/trigger the load of Wordpress native lazy loading images without scrolling?


I don't like lazy-loading because it looks quite ugly for the user in terms of UX. However, I understand the benefits (faster page load, low bandwidth, high PageSpeed scores etc.)

I am planning to write a javascript code which will:

Stay in the bottom > Wait for the page to fully load > After 3 seconds it will work > Force load all the images which were lazy-loaded previously during initial page load

With this, I won't lose any speed scores (because it will load as normal with lazy loaded images) But, also will load the full images when everything is done, so user won't notice. (we do the same for loading live chat scripts. It works pretty nice)

It will probably look something like this:

<script>
window.onload = function() {
    setTimeout(function(){ 
        var ForceLoadImages = document.createElement('script');
        ForceLoadImages.type = 'text/javascript';
        ForceLoadImages.src = 'link-to-the-script-to-force-load-images.js';
        document.body.appendChild(chatScript);
    }, 3000);
};
</script>

I am not a js expert. This was just a dummy example to give an idea. I am specifically asking how to write the content of that "link-to-the-script-to-force-load-images.js" part. Will appreciate any inputs.

There was a similar question here, but need an answer for Wordpress.


Solution

  • I guess that the wp lazy load uses data-src attribute to hold the image and when in view port, its adding the image to the src attribute.

    Simplified like this:

    <img data-src="URL"/>
    

    *if its not like this, find in your source code the attribute where image is hold when out of view

    What you need to do is select all images and change the data-src to src like this:

    var images = document.querySelectorAll('img');
    
    window.onload = function() {
    setTimeout(function(){ 
    for (var i=0; i<images.length; i++) {
        if(images[i].getAttribute('data-src')) {
           images[i].setAttribute('src',images[i].getAttribute('data-src'));
           images[i].removeAttribute('data-src'); // optional if you need to remove data-src attribute after setting src
        }
    }
    }, 3000);
    };
    <div class="container">
    <img data-src='https://picsum.photos/id/237/200/300' />
    <img data-src='https://picsum.photos/seed/picsum/200/300' />
    <img data-src='https://picsum.photos/200/300' />
    </div>