33
I am trying to load a css file dynamically using javascript and cannot use any other js library (eg jQuery).
The css file loads but I can't seem to get a callback to work for it. Below is the code I am using
var callbackFunc = function(){
console.log('file loaded');
};
var head = document.getElementsByTagName( "head" )[0];
var fileref=document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", url);
fileref.onload = callbackFunc;
head.insertBefore( fileref, head.firstChild );
Using the following code to add a script tag to load a js file works and fires a callback:
var callbackFunc = function(){
console.log('file loaded');
};
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
script.onload = callbackFunc ;
head.insertBefore( script, head.firstChild );
Am I doing something wrong here? Any other method that can help me achieve this would be much appreciated?