Loading Javascript dynamically using jquery

If you are creating a web 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 JavaScript 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:

[code lang=”js”]$.getScript(url,callback)
[/code]

Fetches the script specified by the url parameter using a GET request to the specified server, optionally invoking a callback upon success.
Parameters
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
Returns
The XHR instance used to fetch the script.

Usage:
We will load ‘new.js’ dynamically to our web page.

‘new.js’ looks as:
[code lang=”js”]
var testVar = ‘New JS loaded!’;

alert(testVar);

function newFun(dynParam)
{
alert(‘You just passed ‘+dynParam+ ‘ as parameter.’);
}
[/code]

HTML Markup

[code lang=”js”]
<script src="../jquery.js" type="text/javascript"></script>
<script type="text/javascript">// <![CDATA[

$(function()
{
$(‘#loadButton’).click(function(){
$.getScript(‘new.js’,function(){
newFun(‘"Checking new script"’); //This is the external function present in new.js
});
});
});
// ]]></script>
[/code]

[html]
<button id="loadButton">Load</button>
[/html]

Permanent link to this article: https://blog.openshell.in/2011/06/loading-javascript-dynamically-using-jquery/

Leave a Reply

Your email address will not be published.