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:

$.getScript(url,callback)

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:

var testVar = 'New JS loaded!';

alert(testVar);

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

HTML Markup

<html>
<head>
<title>WebSpeaks.in | $.getScript Example</title>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript">
$(function()
{
$('#loadButton').click(function(){
$.getScript('new.js',function(){
newFun('"Checking new script"');//This is the external function present in new.js
});
});
});
</script>
</head>
<body>
<button type="button" id="loadButton">Load</button>
</body>
</html>

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/

2 thoughts on “Loading JavaScript Dynamically using jQuery

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

Comments are closed.