Skip to content Skip to sidebar Skip to footer

Programmatically Load CSS Using JS

I am trying to achieve the following: I have a server-side script that generates CSS code depending on GET parameters On user request a JS should now do the following Load a new

Solution 1:

I know this question is quite old, but in case anyone Googles this, here is a function that lets you define a callback to let you know when the stylesheet is loaded:

    var css = function(url, callback) {

         var head = document.getElementsByTagName('head')[0];
         var cssnode = document.createElement('link');

         cssnode.type = 'text/css';
         cssnode.rel = 'stylesheet';
         cssnode.href = url;

         cssnode.onreadystatechange = callback;
         cssnode.onload = callback;

         head.appendChild(cssnode);
     }

Solution 2:

there are a nice library for this kind of filters...

maybe you can give that a try:

Yep Nope

Yepnope is an asynchronous conditional resource loader that's super-fast, and allows you to load only the scripts that your users need.


Solution 3:

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

Post a Comment for "Programmatically Load CSS Using JS"