Dynamically Load CSS and JS Files
I hear a lot of developers asking about loading
CSS and JS files dynamically.
Surprisingly, creating script and link nodes is just like creating any other nodes.
All you have to do is create them using DOM methods and append to the head:
The Script
Example 1 - JavaScript
First let's load up a JavaScript file. Here's what the external JS file looks like:
And by using the above script, loading it is easy:
Example 2 - CSS
Loading CSS is not much different. Here are the contents of the external CSS file:
Note that you can also use relative URLs or even files on another server:
This has been tested and works in all of the standard browsers including Firefox, Chrome, Internet Explorer, Opera and Safari.
Yeah, loading them is the easy part. Now finding out when they are loaded so you can use them is the hard part.
That’s where YUI’s Get Utility comes in handy:
http://developer.yahoo.com/yui/get/
It will fire an event when the files have been loaded so you know that you can use them.
js frameworks like mootools offer this feature!
I know of this method – but I cannot bring myself to use it – for some reason, it seems really evil to me.
This is not near as evil as using a document.write that has an escaped out script tag as the string which happens all over the place. at least this uses javascript and correct dom manipulation
I use this method successfully… but for some reason it seemd not to work for Opera :-( I can see the DOM node beeing created… but the styles don’t load. Any ideas?
@Miguel: That’s odd. Works for me in XP/9.50…
umm, my js skills are maybe a 7/10 on a good day… but regarding the comment ‘how can u tell if its already loaded’…
cant you do somthing like
function(file,element){
if(document.getElementById(element)){
…
link.id=element;
?