How-To: Load Javascript and CSS dynamically with jQuery

Welcome back to TopSecretProject.

I’ve been working on a new project for Inspire Digital.

The project is going to allow site members to produce their own content.

Members have a WYSIWYG editor (using jquery.wysiwyg) for creating content with some basic HTML. I wanted to come up with a way for only those who need the files to download the files.

Previously in this sort of situation I have simply included the script and css files within the form, but this is not valid HTML.

So … Loading Javascript and CSS dynamically with jQuery to the rescue!

Loading JavaScript is built-in to jQuery, but you need to create CSS elements yourself.

The approach places a class on the text area we want to be WYSIWYG, then we detect that class, load the CSS and JavaScript and initialise the editor. Easy!


$(document).ready( function() {
  if ($('.wysiwyg_editor')) {
    $("head").append("<link>");
    css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "/javascripts/jwysiwyg/jquery.wysiwyg.css"
    });
    $.getScript("/javascripts/jwysiwyg/jquery.wysiwyg.js", function(){
         //wait before initialising to prevent intermittent load error
	 setTimeout("init_wysiwyg_editor()",250);
    });
  }
});
function init_wysiwyg_editor() {
  $(".wysiwyg_editor").wysiwyg();
}

The only gotcha I found was that calling $(“.wysiwyg_editor”).wysiwyg(); would occasionally error with an undefined method unless I put a momentary timeout in before calling. I think this was the result of the browser making the call while still interpreting the freshly loaded script.

7 comments ↓

#1 Luis Aveiga on 09.19.09 at 7:30 am

Hi! Thanks for the post…

I’m trying to load CSS dynamically depending on resolution. Probably your code will help me.

I’ll try it now. Thanks!
Luis

#2 網站製作學習誌 » [Web] 連結分享 on 09.22.09 at 2:06 pm

[...] How-To: Load Javascript and CSS dynamically with jQuery [...]

#3 cha cha on 10.05.09 at 7:36 pm

i dig it

#4 thegreatdao on 10.28.09 at 5:50 am

you should omit the parenthesis in the code of setting timer which should result in setTimeout(“init_wysiwyg_editor”,250);
then you won’t get that errror

#5 gr8karma on 12.16.09 at 3:53 am

You can simplify the element creation a bit using the power of jquery chaining. Try the appendTo method, instead of append:

$(”).appendTo(‘head’).attr({
rel: ’stylesheet’,
type: ‘text/css’,
href: ‘/javascripts/jwysiwyg/jquery.wysiwyg.css’
});

#6 gr8karma on 12.16.09 at 3:55 am

whoops, there should be a <link> in side the jquery selector…

$(<link>)

#7 Justin on 03.25.10 at 4:18 am

Check out the jQuery docs, getScript supports a callback, so you cna put your .wysiwyg function inside of that callback

Leave a Comment