Share

From this page you can share Dynamic Loading of JavaScript without using Eval to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
Dynamic Loading of JavaScript without using Eval
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

Dynamic Loading of JavaScript without using Eval

In trying to create faster loading Ajax applications it is important to reduce the amount of code that is downloaded. One of the best ways to accomplish this is to dynamically load JavaScript as you need it. This will allow that the initial load time is very short.

There are a few ways to accomplish this. One is to have multiple JavaScript files that are loaded using either eval or DOM manipulation (since I am of the school of eval is evil I will use DOM manipulation). The other is to have a server side script (such as a php or ruby script) dynamically create the needed JavaScript based on parameters that are passed through the URL and once again it would be loaded using either eval or DOM manipulation.

No matter which method you choose to use the below code will work to dynamically load the JavaScript. For those of you who have read my post on the JSON Load Object without using Eval (Click here to read the article) the following code will look very familiar as the methods are very similar.

//Dynamic JavaScript Creation
var javascriptload=new Object();
javascriptload.CreateObject=function(codeholderid, url){
	this.codeholderid=codeholderid; //This is the id of the element to hold the script code
	this.url = url;
	this.loadjavascript(codeholderid, url);
};
javascriptload.CreateObject.prototype={
	loadjavascript:function(codeholderid, url){
		var JavaScriptCode=document.createElement("script");
		JavaScriptCode.setAttribute('type', 'text/javascript');
	        JavaScriptCode.setAttribute("src", url);
		document.getElementById(codeholderid).appendChild(JavaScriptCode);
	}
};

In the above code you would pass in the id of the element to hold the JavaScript (this can be a div, body tag or any other tag that can hold a script tag) and you would pass in the URL to the JavaScript (either the separate JavaScript files or the dynamically created JavaScript).

Now that you have the object to dynamically load JavaScript go through your applications and reduce the initial load time in your Ajax applications. You might be surprised just how much faster you can get your applications to load.