How to speed up your site with lazy loading
Sep 9 |
Lazy loading is a process where you defer loading your non-essential scripts and media until after the page loads. With lazy loading, you don't load everything at once, however, you defer the loading of images and scripts until they are actually needed. This is essential if you're trying to improve the load time of your site.
In this technical article, I will show you the process that I used in order to vastly improve the performance of this blog site.
Let's take a second to visually see what lazy loading is by taking a look at my own site. If you navigate to my main blog at www.gregoryalexander.com/blogand slowly scroll down, you will notice that the images do not load until you reach them. When the image is in the viewport, you will notice an image that looks like it is fading in. I am not loading these images when the page loads, but am waiting for you to scroll down before loading them. In order to achieve this effect, we need to have a library that uses the intersection observer API.
This is how the 'big boy's, like Facebook do it. Follow along and I can walk you through in order to do it on your own.
There is a multitude of different lazy loading libraries out there. I have tried a handful of these libraries but settled on defer.jsby shinsenter. My requirements are more extensive than usual. Along with my requirements to lazy load my blog media, I needed to defer the loading of Kendo UI and other extensive libraries such as the Green Sock Animation Platform (GSAP). These libraries need to have a strict order to which libraries are loaded that they depend upon.
I had some issues with a handful of other libraries, but defer.js allowed me to achieve what I need.
Kendo UI needs to have jQuery loaded prior to the extensive Kendo UI scripts, and Kendo UI requires loading a large javascript library along with common .css files, a .less based CSS file that is required by the users chosen theme, and mobile CSS for mobile clients. GSAPalso has several dependencies. I'll go through the process that I used to properly defer these scripts until the page loads defer.js below. At the end of this technical article, I'll discuss how I lazy-loaded the blog media as well.
Before we do anything, we need to insert the defer.js code in the head section of your document:
//* Script to defer script resources. See https://appseeds.net/defer.js/demo.html.
// @shinsenter/defer.js */
!function(e,o,t,n,i,r){function c(e,t){r?n(e,t||32):i.push(e,t)}function f(e,t,n,i){return t&&o.getElementById(t)||(i=o.createElement(e||'SCRIPT'),t&&(i.id=t),n&&(i.onload=n),o.head.appendChild(i)),i||{}}r=/p/.test(o.readyState),e.addEventListener('on'+t in e?t:'load',function(){for(r=t;i[0];)c(i.shift(),i.shift())}),c._=f,e.defer=c,e.deferscript=function(t,n,e,i){c(function(e){f(0,n,i).src=t},e)}}(this,document,'pageshow',setTimeout,[]),function(u,n){var a='IntersectionObserver',d='src',l='lazied',h='data-',p=h+l,y='load',m='forEach',r='appendChild',b='getAttribute',c=n.head,g=Function(),v=u.defer||g,f=v._||g;function I(e,t){return[].slice.call((t||n).querySelectorAll(e))}function e(s){return function(e,t,o,r,c,f){v(function(n,t){function i(n){!1!==(r||g).call(n,n)&&(I('SOURCE',n)[m](i),(f||['srcset',d,'style'])[m](function(e,t){(t=n[b](h+e))&&(n[e]=t)}),y in n&&n[y]()),n.className+=' '+(o||l)}t=a in u?(n=new u[a](function(e){e[m](function(e,t){e.isIntersecting&&(t=e.target)&&(n.unobserve(t),i(t))})},c)).observe.bind(n):i,I(e||s+'['+h+d+']:not(['+p+'])')[m](function(e){e[b](p)||(e.setAttribute(p,s),t(e))})},t)}}function t(){v(function(t,n,i,o){t=[].concat(I((i='script[type=deferjs]')+':not('+(o='[async]')+')'),I(i+o)),function e(){if(0!=t){for(o in n=f(),(i=t.shift()).parentNode.removeChild(i),i.removeAttribute('type'),i)'string'==typeof i[o]&&n[o]!=i[o]&&(n[o]=i[o]);n[d]&&!n.hasAttribute('async')?(n.onload=n.onerror=e,c[r](n)):(c[r](n),v(e,.1))}}()},4)}t(),u.deferstyle=function(t,n,e,i){v(function(e){(e=f('LINK',n,i)).rel='stylesheet',e.href=t},e)},u.deferimg=e('IMG'),u.deferiframe=e('IFRAME'),v.all=t}(this,document);
This script is short, and it can be either placed inline, or you can grab the code via CDN at https://github.com/shinsenter/defer.js/.
Defer Kendo UI.
Kendo UI requires loading the following files- in this order:
- jQuery (not deferred)
- kendoUiCore.js (or kendoUiAll if you're using your own license).
- The kendoUi common .css file.
- The kendoUi theme .css file.
- And the kendoUi mobile .css file
Here is how I achieved this in actual code. This code also needs to be placed in the head section of the page underneath the defer.js code:
<script type="deferjs">
// Kendo common css. Note: Material black and office 365 themes require a different stylesheet. These are specified in the theme settings.
$('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', '/common/libs/kendo/styles/kendo.common.min.css') );
// Less based theme css files.
$('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', '/common/libs/kendo/styles/kendo.silver.min.css') );
// Mobile less based theme file.
$('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', '/common/libs/kendo/styles/kendo.silver.mobile.min.css') );
</script>
Note the defers in the script type. This is a keyword used by the defer.js library to defer these scripts until page load. Here, all of the Kendo UI resources are deferred other than the jQuery library.
Defer GSAP and ScrollMagic resources.
GSAPis an amazing library if you're interested in cutting-edge animation effects. I use GSAP and ScrollMagic to provide for my parallax effects. See the entry Introducing Galaxie Blog for an example of a parallax effect.
My requirements to load GSAP and SrollMagic are:
- Load the tweenMax javascript library
- Load scrollMagic
- Load the main GSAP library
- Load the scrollToPlugin library
- And load my GSAP debugging script
Allof the GSAP resources will be deferred until page load.
Here is the code:
<script type="deferjs" src="/blog/common/libs/greenSock/src/uncompressed/TweenMax.js"></script>
<script type="deferjs" src="/blog/common/libs/scrollMagic/scrollmagic/uncompressed/ScrollMagic.js"></script>
<script type="deferjs" src="/blog/common/libs/scrollMagic/scrollmagic/uncompressed/plugins/animation.gsap.js"></script>
<script type="deferjs" src="/blog/common/libs/greenSock/src/uncompressed/plugins/ScrollToPlugin.js"></script>
<script type="deferjs" src="/blog/common/libs/scrollMagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js"></script>
Note: typically, the GSAP libraries are loaded at the end of the page, however, this did not work for me. I found that these files must be loaded in the head section.
Lazy loading media files.
My open source Galaxie Blogallows blog owners to upload picturesand media that show up on the top of every blog post. However, on the main blog page, this necessitates the client to download quite a lot of extra data. In order to achieve a decent page load time I had to figure out a way to delay the loading of this media. I also wanted to convey to the reader that something was happening and alert them with a subtle css effect when a new picture is loaded. Here is the defer.js approach:
CSS:
/* Lazy loading image classes */
/* Initially hide the element with zero opacity */
.fade {
transition: opacity 500ms ease-in-out;
opacity: 0;
}
/* Show it with the 'shown' class */
.fade.shown {
opacity: 1;
background: 0 0;
}
Javascript:
// Lazy loading images and media.
// Callback function to add the 'shown' class into the element when it is loaded
var media_loaded = function (media) {
media.className += ' shown';
}
// Then call the deferimg and deferiframe methods
deferimg('img.fade', 300, 'lazied', media_loaded);
deferiframe('iframe.fade', 300, 'lazied', media_loaded);
Place the script and the CSS anywhere in your document as long as it is above the media that you're about to lazy load. Place the following javascript at the end of the page:
// Lazy load the images.
deferimg('img.fade', 100, 'lazied', function(img) {
img.onload = function() {
img.className+=' shown';
}
});
Finally, include your image like so:
<img class="fade" data-src="https://gregoryalexander.com/blog/enclosures/8_31.png" alt="">
I'll quickly try to explain what is going on here. If you look carefully, you'll notice that the " src" tag is missing from the above image. The media does not show at first due to the src tag that is missing, and the opacity setting that is initially set to zero. When the defer.js library notices that the user has scrolled to the viewport where the image resides, defer.js takes the string found in the data-src tag and automatically builds the src dynamically. When the image is loaded to the client, the CSS briefly fades in.
You can use the same approach to defer and lazy load pretty much anything. If you're interested, you can dig into the meaty details by looking at my source code, or checking out the excellent defer.js demo.
Related Entries
Tags
Lazy LoadingThis entry was posted on September 9, 2019 at 5:29 AM and has received 3768 views.