Loading sub-menu...

How to load JavaScript dynamically with jQuery

This article describes how to load JavaScript files dynamically and asynchronously by using jQuery's AJAX interface. Loading scripts asynchronously can help both you and your users in a number of ways. For example:

  • Being able to load JavaScript dynamically can help inspire better modularization of your code. Since you will have a useful strategy for loading discreet modules when needed, you will be more apt to write your code in modules that are smaller, easier to understand, and easier to maintain.
  • It can hep you make web pages more responsive. You will be able to load only the minimal JavaScript required and then additional modules as needed or in the background.
  • It gives you a new mechanism for functional capability; you might use it to dynamically change JavaScript depending on user behavior.

Here's how it is done. The following line will load and execute the file 'my-library-core.min.js'.

As you can see, it's quite simple. You can also provide a callback function that will be executed immediately after the given JavaScript file has been loaded and executed.

As of jQuery version 1.2, you can use this method to load scripts from any domain - not just the domain from which your app is accessed.

It seems that the path to the JavaScript file must be relative to the HTML page from which the getScript method is being executed rather than relative to the script file itself. In other words, if 'index.html' includes 'js/my-core.js' and my-core.js has the getScript that is executed, then the path would be 'js/my-module.js'. One could easily assume that since my-core.js executes the getScript method, then the path needs to be relative to it (i.e. 'my-module.js'), but remember that it is actually being executed in the context of the HTML page in which it is included (and thus must be 'js/my-module.js').

In case it helps, here is snippet of my own code that uses this feature:

You can find more information about this feature on jQuery's Ajax/jQuery.getScript page. If you're new to jQuery and appreciate simple tips like this, consider purchasing the full-color book that's chock-full of them called "Beginning JavaScript and CSS Development with jQuery," by Richard York. It is from Richard's book that I learned about this and many other cool things jQuery can do.

Labels

jquery jquery Delete
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.