scriptNode

Web development with a focus on JavaScript RSS

Dynamically Load CSS and JS Files

Novice Matt Hackett Published September 28th, 2008 by Matt Hackett

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.

Read other articles tagged: , , ,

Comments (7)

  • Dav Glass

    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.

  • Ralf Lauther
    September 28th, 2008 Ralf Lauther said…

    js frameworks like mootools offer this feature!

  • Binny V A

    I know of this method – but I cannot bring myself to use it – for some reason, it seems really evil to me.

  • davidm
    September 29th, 2008 davidm said…

    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

  • Miguel
    December 28th, 2008 Miguel said…

    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?

  • Matt Hackett

    @Miguel: That’s odd. Works for me in XP/9.50…

  • tom3k
    June 22nd, 2009 tom3k said…

    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;

    ?

Thoughts?

(required)

(not shared)

© 2010 scriptNode