Loading JavaScript Dynamically using jQuery

If you are creating a web2.0 application, then your web pages may have all possibilities of being overwhelmed with a number of JavaScript files. Including large number of JavaScript files may slow down your web page. So its a good idea to load JavaScripts dynamically to your web page, i.e load them only when these are needed. This strategy can help you reducing the load time of your web pages. Fortunately jQuery comes with a built in utility for this feature. The $.getScript function of jQuery provides us this power. The function works like simple AJAX call that includes the remote JavaScript files dynamically in our web page. Lets see the syntax of this function:
Fetches the script specified by the url parameter using a GET request to the specified server, optionally invoking a callback upon success.
url (String) The URL of the script file to fetch.
callback (Function) An optional function invoked after the script resource has been loaded and evaluated.
The following parameters are passed:
¦ The text loaded from the resource
¦ The string success
The XHR instance used to fetch the script.

We will load 'new.js' dynamically to our web page. 'new.js' looks as:
var testVar = 'New JS loaded!';


function newFun(dynParam)
 alert('You just passed '+dynParam+ ' as parameter.');

HTML Markup
<title>WebSpeaks.in | $.getScript Example</title>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
   newFun('"Checking new script"');//This is the external function present in new.js
<button type="button" id="loadButton">Load</button>


And what if your callback needs to manipulate a dom element ? How are you sure dom is already loaded ?

Anonymous - onload is your friemd

We would love to hear from you...

back to top