Satya’s Weblog

Spartan attitude !

dynamic loading javascript and css.

Posted by satya on October 19, 2008

Offlate….im enjoying my run thru web-development….once i started using AJAX. When i started 2 feel the spirit of AJAX…..i realized that…its taking too long a time to load the AJAX page. The reason……when the page is loading…it also loads the required JAVASCRIPT FILES entirely.

My page has a lot of AJAX functionality……theres no guarantee that the user is gonna use all of those functionalities. So, in that case……loading of all the javascript is not justified.  Then the question rises……is there a way where the javascript is loaded on demand…i.e Only when an ajax functionality is called….load the javascript required . Else, forget it.

Then, I thought……..NO WAY….But asusual……i found it as POSSIBLE.

This is called dynamic loading of JAVASCRRIPT. This is no different from creating an ELEMENT in HTML dynamically.  To create a TEXT INPUT ( <INPUT TYPE=”TEXT” name=”txt” /> ) dynamically….the code is follows:

var textInput  = document.createElement(“INPUT”);

textInput.setAttribute(“type”,”TEXT”);

textInput.setAttribute(“name”,”txt”);

Now, to add this element to a DIV whose id is say…div_id, we say:

document.getElementById(‘div_id’).appendChild(textInput).

So, following the same…..

to add a script, the HTML tag we use is <SCRIPT TYPE=”TEXT/JAVSCRIPT” src=”script.js” />.

Now to add this dynamically:

var fileRef = document.createElement(’script’);
fileRef.setAttribute(“type”,”text/javascript”);
fileRef.setAttribute(“src”,”script.js”);
document.getElementsByTagName(“HEAD”)[0].appendChild(fileRef)

What we are doing here is that: create an element, assign its to type=”text/javascript” , src=the script we wanna load. And add it to the HEAD element of HTML.

Thats it. …As simple ad that…Go ahead and make ur AJAX pages light weighted…….As im making my HTML PAGES very……lightweighted.

Also, u can also load CSS dynamically.

Also, also, also……U van remove the javascript and css dynamically. I dont think i have to explain why would one have to remove them. Its quite straight forward.

Reference

Satya — EVENTZS

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>