How to Use a Javascript Loader to Speed Up Your Site

fastcheetah

Performance has been a major focus for the last few years, but it’s easy to get lazy.

We presume that because internet connections are getting faster and browsers are growing more powerful – site speed doesn’t really matter so much.

This presumption is unfounded. Something that I came to realize when reviewing speed on Caffeine Informer.

I had ticked off all the usual suspects:

  • Ensuring Gzip and expires headers were set properly on the server.
  • Reduced http calls by using a CSS sprite for icons and other images.
  • Used a caching solution (in this case W3 Total Cache for WordPress).
  • Kept a close eye on bloat (common to many WordPress installations – typically too many plugins).

Mobile is Slow

Not everyone is using Chrome on a powerful desktop. And, depending on your site statistics, many users may be hitting it with a slow mobile connection, running on a slow mobile browser).

Performance is an issue.

Making Faster Javascript

Many sites call a number of Javascript files in the header. If you’re using a library like jQuery, followed by a bunch of plugins, this can really blow out.

Loading and parsing of a JavaScript file blocks page rendering. This means that your page will not display until each script call in your document head has been loaded and executed.

There are some techniques you can use to address this.

Advertisement

1. Combining Scripts

There is so much contrary advice about this. If you have 4 scripts of 20k each, you could combine them into 1 and have a single call of 80k. If you leave them separate then a modern browser can call all 4 at once, and then parse one by one. Which is fastest?

This is difficult to measure, but after lots of experimenting with this, I feel it is best to combine smaller scripts into 1 larger file.

If you have larger files they could be left separate allowing them to be called at the same time.

2. Minify Scripts

The minify process will take a script, remove comments and newlines, and rename big variable names in order to make the file size small.

Minifying can be done in a number of ways: On WordPress the W3 Total Cache plugin will combine and minify. Other plugins such as wp-minify will also do this.

You can use an online tool such as the YUI compressor or PimpMyJS.

You can also install a compressor on your development machine and minify before upload.

3. Using a Script Loader

A script loader is a piece of Javascript that manages the loading and parsing of other scripts.

At first I avoided this as it seemed counter-intuitive; in order to make my Javascript faster I was supposed to add yet another script to the mix. This is a misunderstanding.

There’s a lot of script loaders out there. We used HeadJs. It has a small footprint and also offers feature detection code like Modernizr.


<head>
  <script src="/wp-content/js/head.99.min.js"></script>

Then, the following code:


head.js(
   {jquery: "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"},
   {app: "/wp-content/js/app.ef15r.1.js"},
   {tbls: "/wp-content/jquery.dataTables.1.9.min.js"}
);

This will queue the three scripts asynchronously, making sure that they are parsed and executed in the order listed. There is no blocking of page rendering.

Later on the foot of the document we can test if a certain script has loaded, and do something.


head.ready("tbls", function() {
    if (typeof doDataTables == 'function') {
        doDataTables();
    }
});

Be careful of using jQuery’s document ready $(document).ready() – you can get yourself in a world of pain as you have no guarantees of when the script has loaded and executed. If it’s cached it’s probably already there. If not, the DOM might be rendered with still no parsed script.

Make sure any functions using jQuery’s $ are executed only when jQuery has loaded.  Some good discussion about loading asynchronous jQuery here.

Here is the timeline (from Chrome) on a rather slow connection. The latency is terrible (around 500ms). The blue line shows when the DOM is ready.

waterfall1

What you find with asynchronous Javascript is that the total page load time (i.e. testing with a tool like Pingdom) doesn’t change BUT the page appears much quicker on the browser. The 3 scripts above would normally have blocked rendering, but instead are loaded in parallel alongside the rest of the document.

Typically the page appears in less than a second, with functionality arriving slightly later.

As the size of Javascript required for a typical site continues to grow, a more comprehensive understanding of how scripts are loaded is needed. This is only going to get worse as developers must work with ever more devices, and multiple input methods (such as touch).

Hi, I'm James, and for the last decade I've made a living by making my own blogs and websites.
Updated: September 15, 2016

10 Comments

  1. If you’re using jQuery, it has already provide a function that similar to Javascript Loader. I use the following code on my website.

    For example:

    $.when(
    $.getScript( "/assets/jfu/js/vendor/jquery-ui.min.js" ),
    $.getScript( "/assets/jfu/js/jquery.fileupload.js" ),
    $.getScript( "/assets/jfu/js/jquery.iframe-transport.js" ),
    $.Deferred(function( deferred ){
    $( deferred.resolve );
    })
    ).done(function(){
    // After loading those js files, you can do something here
    }

    And if your website doesn’t use many javascript, put the javascript all together directly in head, you’ll get high score in PageSpeed Insights , My site (http://vbuz.com) scores 100 in PageSpeed Insights, it is a good example.

    • thanks, I didn’t know that. What I like about what jshead is that you are not dependent on jquery loading and parsing, but can already begin the async load process.

  2. So how to remove render blocking jquery on Blogger

  3. Thanks for the great post. For minifying my JavaScript files, I prefer the online tool on http://www.blimptontech.com They use UglifyJS to get the compression done. Which gives you a little obfuscation as well. One cool other feature that I have started to use a bunch is the combining of JS files. You can easily upload a bunch of files, it adds them all to a single one, then minifies the JS.

    • Hi, Is this a tool you have made? Thanks for sharing. UglifyJS is pretty much the new standard on compressing JS code.

      • It is a fork of a project that I have modified. I have updated the backend quite a bit, and still working some more on it for a better end result. So far I am very happy with the results it is giving. I am also going to add in CSS ability as well. If you have any suggestions feel free to let me know as it is just a fun project so I could learn more about NodeJS.

        I agree though UglifyJS is the “standard” I have had zero issues minifying my JS scripts this way. Even once it shrinks the variables and everything. On average I am getting 40-60% reduction in my file sizes.

Add a Comment