tags:

views:

56

answers:

2

hi,

i want to load css files on demand (by eg. running a xmlhttp request which returns the css files to be loaded) for example: style1.css, style2.css ..

so - is there a way in jQuery (or a plugin) to this:

  • bulk-loading several files + adding all those css-files into the dom
  • when finished loading: firing a callback (like alerting "all stylesheets are finished loaded!");

the idea is: loading html via xmlhttp, loading +adding required css-files, then - after anything is finished, display that html.

any ideas? thx

+8  A: 

Here is how I would load it:

$(document).ready( function() {
    var css = jQuery("<link>");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "path/to/file/style.css"
    });
    $("head").append(css);
});
Whit
thx looks great but i need to load those css-files on demand after jQuery has already been loaded .. :/
Fuxi
Right, the $(document).ready event will fire after jQuery has already been loaded.
Whit
He probably means a click or some other action, $(document).ready() isn't really **on-demand** :) He should've specified however.
Marko
@Fuxi - so then just change `$(document).ready(...)` to whatever event you want to trigger it, e.g.: `$('selector').click(...)`.
Matt Huggins
A: 

If you want it to by dynamic (read: on demand) you can modify Whit's response to loadCssFile() and call that with the file you want to load.

function loadCssFile(pathToFile) {
    var css = jQuery("<link>");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: pathToFile
    });
    $("head").append(css);
}
Robert