I was searching an easy way to do lazy load in a site that loads a lot of images in image tags. I found a lot of plugins but nothing that solve my problem with simplicity. So i decide to write myself:

See working:

The particular challandge here was how to stop load any image before removing the src attribute and preventing the load itself.. Well, using the image tag to execute this script i finnaly got it.

  <img onerror="
    var m = document.querySelectorAll('img:not([onerror])'), w = window;
    for(i = 0; i < m.length; i++)
        m[i].setAttribute('lazy',
        m[i].getAttribute('src')),
        m[i].removeAttribute('src');
    var lazy = function(){
        var imgs = document.querySelectorAll('[lazy]');
        for(i = 0; i < imgs.length; i++){
            var o = imgs[i], lazy = o.getAttribute('lazy');
            if(o.y <= (w.screen.height + w.scrollY + 50) && o.y >= ( w.scrollY - 50)){
                o.setAttribute('src', lazy);
                o.removeAttribute('lazy');
            }
        }
    }
    w.onload =  w.onscroll = lazy;
" src/>

The only thing you may pay attention is on putting this image tag hack before all the content of your site, i advice you to put this code after the body opening tag.


4,596 2 40