Controlling JavaScript with LazyLoad – a ShareThis example

Forgive me for the break in communication. Let’s get right back into it.

In the last few months I’ve been looking into website load times and implementing a few on my own. My hoster doesn’t run the most efficient servers and so my webpages really weren’t appearing as first as they might. One interesting area I looked into was javascript – in particular how the position and method of including can impact the rendering of a webpage and the speed it appears.

Some of the worst things you can do is include javascript files near the top of your HTML page. Unless you are careful, any javascript you include in the <head> or <body> sections will stop a browser from reading and rendering your page. This is because the browser does not know whether or not that javascript will output code and therefore require some rendering of its own.

Defer and Async

The good news is you can tell a browser that it’s all right to skip this script till later with defer and async. Defer has been around for many years starting in IE4, it simply tells the browser that the piece of code can be run at a later time, probably just after the DOM finishes loading but there’s no guarantee. Async is a relative new coming and is similar to defer except the script will run as soon as it can, along side whatever else the browser is rendering. It’s safe to use both, async will take precedence in browsers that recognise it:

<script type="text/javascript" src="awesome.js" defer="on" async="on">
</script>

Script Create

Another way to control javascript loading is by programmatically creating script tags with javascript. The advantage is that you can have a callback function triggered when the external javascript has completed loading. First we create the tag then we append it to the page, like so:

var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.onload = function() { /*  Do something amazing */ };
newScript.src = '/js/myscript.js';
document.getElementById('head')[0].appendChild(oScript); // add to page

Unfortunately, certain browsers – namely IE – do things differently (more info here). But the good news is the internet is full of smart and generous people and one of them has created a cross browser library to do the hard work for you.

LazyLoad

From: https://github.com/rgrove/lazyload

Using LazyLoad all you have to do is write a few lines of javascript and you can set additional code to trigger as soon as the javascript loads. For instance:

LazyLoad.js( 'jquery.min.js', function () { 
    $('a').click( function() { alert( "jQuery Loaded" ); } );
});

In addition you can also LazyLoad CSS files too. You do of course still have to include the LazyLoad javascript file itself: you can include it in the head of your page with the defer and async attributes, and then either assume the small file is already loaded by the end of the file, or you can include any LazyLoad calls in the window.onload event which is guaranteed to have completed loading LazyLoad before it fires.

<script type="text/javascript" src="lazyload-min.js" defer="on" async="on">
</script>

Remember we are trying to move the majority of the javascript loading to a point after our page has been rendered.

ShareThis example

Here’s an example using the really ShareThis javascript include. ShareThis creates buttons on your website so that anyone reading can share via other sites (such as Twitter, WordPress, etc). Loading of the javascript from the servers can be quite slow and using the suggested way to include the code can produce noticable delays in rending you page. So lets hand it off to LazyLoad. (Incidentally the ShareThis javascript file at 119000 bytes is more than 100 times larger than LazyLoad file at only 1700 bytes ).

The suggested way to include the ShareThis buttons is with this piece of code:

<!-- from http://sharethis.com/publishers/get-sharing-tools -->
<script type="text/javascript">var switchTo5x=false;</script>
<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript">
  <span class="brush: javascript;">
    stLight.options({publisher: "UUID", doNotHash: true, doNotCopy: true});
  </span>
</script>

This simply loads the file as soon as it is specified in your webpage. But here’s the better LazyLoad way:

<script type="text/javascript">
   window.onload = function() {
      var switchTo5x=false;
      LazyLoad.js( 'http://w.sharethis.com/button/buttons.js', function () {
         stLight.options( 
            { publisher: "UUID", doNotHash: true, doNotCopy: true }
         );
      });
    }
</script>

Here the code is wrapped in the window.onload event, so this code only gets executed after the document has loaded. We then start the load of the ShareThis code, automatically async, and the final initialization stLight.options is done once the file has loaded.

Summary

So if you’d like to use this nice library with ShareThis, here’s what you need to do:

1) Add the LazyLoad javascript to your <head>:

<head>
...
<script type="text/javascript" src="lazyload-min.js" defer="on" async="on">
</script>
...
</head>

2) Place the collection of ShareThis buttons where you need them in the <body> e.g.:

<body>
...
<span class="st_twitter_large" displayText="Tweet"></span>
...

3)  Then at the end of your <body> add the javascript load code (with your publisher id):

...
<script type="text/javascript"> 
  window.onload = function() {
    var switchTo5x=false; 
    LazyLoad.js( 'http://w.sharethis.com/button/buttons.js', function () {
      stLight.options( 
        { publisher: "YOUR-UUID", doNotHash: true, doNotCopy: true } 
      );
    });
  }
</script>
...
</body>

There are other libraries similar to LazyLoad, but none as compact. Let me know if you find it useful.

🙂

3 Replies to “Controlling JavaScript with LazyLoad – a ShareThis example”

    1. Hi Richard,

      Thanks for the comment, I should have noticed it might not be obvious how to use this! I’ve added a summary at the end which explains what you need to do. Hope that makes things easier.

      Thanks

      Mat

  1. You may also want to load LazyLoad from a Content Delivery Network (CDN). CDNJS has some superb uptimes. The url for lazyload is:

    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lazyload/2.0.3/lazyload-min.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.