jQuery

Load Scripts Dynamically With jQuery

A common tactic to help speed up your website is to use a technique called lazy loading which means that instead of loading everything your page needs at the start it will only load resources as and when it needs them.

For example you can lazy load images so you can start the page off only with the images you need to view the page correctly, then other images that are out of view you won't need to load straight away. As the user scrolls down the page you can then search to see if the images are about to come into view and lazy load the images when they are needed.

You can do the same with other resources such as JavaScript or CSS files, you can make sure you only load in the script as and when they need them to be used.

An example of this I have used in the past is loading Disqus comments on the click event of a button, this jQuery code will then load in the Disqus Javascript file and initialise the Disqus code on the selected div.

$j=jQuery.noConflict();

$j(document).ready(function() {
	$j('.showDisqus').on('click', function(){   // click event of the show comments button
		var disqus_shortname = 'enter_your_disqus_user_name';  // Enter your disqus user name

                // ajax request to load the disqus javascript
		$j.ajax({
	         type: "GET",
	         url: "http://" + disqus_shortname + ".disqus.com/embed.js",
	         dataType: "script",
	         cache: true
	     });

	        $j(this).fadeOut();  // remove the show comments button
	});
});

Ajax Method

As you can see from the code above we have a click event of the .showDisqus button, inside this using the jQuery method .ajax() which is making a GET request for the script of embedding Disqus into your application.

The ajax method is normally used to make basic http requests to a server side script and return the output of the script. On this occasion we are making a GET request and setting the dataType to be a script. This tells jQuery to treat the return as if we are including a new JavaScript file, this will disable browser caching on the script by adding a timestamp parameter to the end of the script.

If you would like to enable caching of the script then you need to make sure you include a cache: true parameter.

$.ajax({
    type: "GET",
    url: "http://test_script.js",
    dataType: "script",
    cache: true
});

Get Script Method

Another option to get the script via GET ajax is to use the method getScript() this is simply a wrapper for the above ajax method.

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

This allows you to reduce the amount of code you are writing by simply using this method.

$.getScript( "http://test_script.js" )
  .done(function( script, textStatus ) {
    alert('Successfully loaded script');
  })
  .fail(function( jqxhr, settings, exception ) {
    alert('Failed to load script');
});

The problem with using getScript() is that it will never cache the script as it will always add the timestamp querystring to the end of the JavaScript file. As the ajax() method allows you to choose if you cache the script or not it is better to use this method when loading in a script that will not change.

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

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