jQuery Lazy Loading Images with Simple Example
This week I stumbled upon a great mystery of Lazy Loading. I have seen this effect on multiple websites but never an example of how to do it.
The basic idea is that when you have many images on a website, they tend to take a lot of time to load when user connects to your website. With lazy load we can prevent the loading of these images until user should see them.
Lazy Loading #
There are variety of plugins and addons made to do this but I found them quite complicated and maybe too little of a function to come from a separate plugin. So why not do it ourselves if we could find a direction to the right path? Lazy loading can sound big project but it really isn’t, and really doesn’t need a plugin to do the work for you.
I have also made function called lazyload, which goes through all lazyload classed elements on the page and shows them by setting data-src to the elements src. By doing this the browser knows to load the received source data and that way shows the image to the user. I have attached also a event listener to scrolling so that when user scrolls the function is loaded.
The elements which you want to lazy load, in this case the images, need to have lazyload class attached into their HTML code. Also remember to insert the original image src to data-src attribute.
<img class\="lazyload" data\-src\="golden-star.png" alt\="Golden Star" /\>
That was it! I hope you enjoyed the example. Please post a comment if you have something in mind about this!