2

Is there any way to inject a css file or javascript file dynamically into the head tag of an HTML document.

Here is the scenario :

I make an ajax call, it basically brings back some HTML, the css and events are stored in a separate file.

What i need is, that the link and scripts are put into the head tag.

Aroha Labs
  • 162
  • 9

2 Answers2

1

Loading external JavaScript is built into jQuery, but you'll need to create the CSS elements:

$(document).ready( function(){

    $("head").append("<link>");
    css = $("head").children(":last");
    css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "/link/to/your.css"
    });
    $.getScript("/path/to/your.js", function(){
         // fires after JS is loaded
    });

});

You will need to be able to load jQuery and run this JavaScript on the page, in order to pull in your external files.

I used Google to find: http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/

Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
  • 1
    FYI, older IE versions will not allow jQuery to mess with the document head. – peteorpeter May 09 '12 at 14:53
  • heh, well then it might not be such a good idea to play with it.. by the way do you know which version doesnt.. i mean IE7 or IE8 – Aroha Labs May 09 '12 at 14:57
  • 1
    I believe it is IE8 and below. IIRC, you may be able to add the as a node, but the CSS doesn't register/apply unless you call `createStyleSheet`. – peteorpeter May 09 '12 at 16:06
1

The jQuery method doesn't work in IE, but you can handle that with it's own special creatStyleSheet function:

var url = '/b/css/datepicker.jquery-ui.css';

if (document.createStyleSheet){
  document.createStyleSheet(url);
 } else {
   $('head').append('<link rel="stylesheet" type="text/css" href="' + url + '"/>');
 }
peteorpeter
  • 4,037
  • 2
  • 29
  • 47