AJAX - $.load(), $.getScript()

The $.load() method

The $.load is used to load content via AJAX and place it directly into a targeted element. When $.load is pointed at a HTML page it will copy the content inside of the <body> tags. The syntax for $.load is as follows:

$.load(url, [data], [callback]);

In the following example assume we have a HTML page with the following content in a file called 'toLoad.html'.

<h1>The joy of coding</h1>
<p>Will it ever end.</p>
<p>The final paragraph.</p>

This can then be loaded into another file with jQuery and placed into a selected element. For example the following will load the HTML from the 'toLoad.html' file into the <div> of ID 'newContent'.

$('div.newContent').load('toLoad.html');

See a working demo.

Sometimes you don't want the whole of the HTML to be inserted. To do so simple amend the $.load with a selector indicating which part of the document you wish to load. For example the following will only load the paragraphs from the 'toLoad.html' file.

$('div.newContent').load('toLoad.html p');

See a working demo.

The $.getScript() method

The $.getScript() method allows Javascript files to be loaded programmatically. For example you may only want a script to be loaded based on some logic within your Javascript. I have found this useful when using Modernizr to detect support for the HTML5 <video> element, and then loading either some Javascript to support the HTML5 or some Javascript to load a Flash video fallback. For example:

if(Modernizr.video){
	$.getScript("five.js");
}else{
	$.getScript("swfobject.js");
}

The $.getScript() also supports a callback function ie:

$.getScript("five.js", function(){
    console.info('Ready to go!');
});

Leave a Reply

*