I discussed in my previous post a function I’d came upon through searching that allows HTML that is appended to the DOM through AJAX which includes SCRIPT tags to wait until they have loaded before firing ready events. Upon testing it in Firefox, I found that it wasn’t working in some scenarios, so I began searching again and found LABjs. LABjs stands for Loading and Blocking JavaScript and allows you to chain loading of scripts together and end that chain with a function that gets called back. The nice thing is you can choose to use the word “wait” between load methods and it will block before loading the next, or if you omit the wait, the scripts will load in parallel, speeding up load time of your web application.

Here’s an example. Let’s say you have a site that loads a partial section of HTML from an AJAX request and you’re going to append it to the page, but it includes some scripts in it. Your script is dependent on two other publicly hosted scripts (twitter, Google maps for example) and can’t execute until those are finished loading. Rather than load them in your main page and increase startup time, LABjs handles it perfectly:

Old AJAX response HTML:

<script src=”http://publicwebservice1.com/script1.js” />
<
script src=”http://publicwebservice2.com/script2.js” />
<!– This can’t execute until the first two scripts have loaded, but not all browsers load these in order in a dynamic update to the DOM! –>
<script src=”myscript.js” />

Old myscript.js contents:

<script type=”text/javascript”>
$(document).ready(function() {
// This will fail if the first two scripts haven’t loaded yet
var script1Object = new PublicWebService1.APIObject();
var script2Object = new PublicWebService2.APIObject();
}):
</script> 

Replacing this with LABjs becomes:

<script type=”text/javascript”>
$LAB
.script(http://publicwebservice1.com/script1.js&#8217;)
.script(http://publicwebservice2.com/script2.js&#8217;).wait()
.script(‘myscript.js’).wait(function() {
var script1Object = new PublicWebService1.APIObject();
var script2Object = new PublicWebService2.APIObject();
});
</script>

Category:
javascript, presentation, technologies

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: