LA.NET [EN]

Aug 19

Deferred script loading is a technique which can be used to reduce the initial loading time of any page. The idea is to load only the basic JavaScript code that is necessary for the initial loading operations of the page and then perform additional downloads for features that the user *might* use after initial rendering.

This is a fairly known and common technique and you’ll even find a pattern called On-demand JavaScript on the AJAX patterns web site. JQuery helps by introducing the utility $.getScript function. To illustrate its use, lets assume that we’ve got a button that won’t be *heavily* used and that relies on several JavaScript lines of code. This is a scenario where the user experience can be improved by using deferred script loading.

We’ll be simulating this by using a simple JS file (called hi.js) with the following code:

function sayHi(name) {
    alert(name);
}

Since we’re facing lots of JS lines (please imagine it:),,) and this code isn’t necessary for the initial load of the page, we’ve decided to run it only when needed, ie, only when someone clicks the say Hi button. Here’s the code we might ended up writing:

<input type="text" />
<input type="button" value="Server" />
<script type="text/javascript"> $(function() { $("input[type=button]").click( function(evt) { if( !window.sayHi ) { evt.target.disabled = "disabled"; $.getScript("hi.js", function() { sayHi($("input[type=text").val()); evt.target.disabled = ""; }); } else{ sayHi( $("input[type=text").val() ); } }); }); </script>

It might seem complicated, but it’s not. Since we’re loading an JS file, we need to make sure that we’ll only load it once (loading several times the same user file doesn’t really do much for improving the user experience, right?). The easiest way to do that is to check for the existence of the sayHi function (it will be defined after the successful load of the JS file). To ensure that the user won’t click the button twice before the file is loaded, we need to disable it and enable it when the JS code has been loaded and evaluated (which is perfect for the callback function we can pass to the $.getScript function).


And that’s it. Keep tuned for more on JQuery.

3 comments so far

  1. cloudgen
    1:59 am - 8-29-2009

    Your article is good. One point to mention, $.getScript can also be used for loading external javascript file (backuped in other server) once the original javascript file is not available (maybe store in public server).

  2. Frirari
    5:01 am - 10-11-2009

    Very interesting site. Hope it will always be alive!,

  3. Nieswen
    9:39 am - 10-12-2009

    Great. Now i can say thank you!,

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>