Saturday, March 19, 2011

Loading JavaScript Dynamically using jQuery

3/19/2011

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 is a web developer, programmer and blogger. He has expertise in PHP, Magento, WordPress, jQuery, JavaScript, HTML5 and CSS3. He loves to develop good looking websites with strong backend.

2 comments :

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

    ReplyDelete
  2. Anonymous - onload is your friemd

    ReplyDelete

We would love to hear from you...

 

© 2014 Web Speaks . All rights resevered. Designed by Templateism