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?
You can make an empty css link in your html file and give the link an ID. e.g
then call it with ID name and change the 'href' attribute
yepnope.js can load CSS and run a callback on completion. e.g.
Unfortunately there is no onload support for stylesheets in most modern browsers. There is a solution I found with a little Googling.
Cited from: http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof
The basics
The most basic implementation of this can be done in a measely 30 lines of — framework independent — JavaScript code:
This would allow you to load a style sheet with an onload callback function like this:
Or if you want to your callback to maintain its scope/ context, you could do something kind of like this:
Some time ago i made a library for this, it's called Dysel, i hope it helps
Example: https://jsfiddle.net/sunrising/qk0ybtnb/
This vanilla JS approach works in all modern browsers:
Here's how we do it. By using "requestAnimationFrame" (or fallback to simple "load" event if its not avail).
By the way, this is the way Google recommends in their "page-speed" manual: https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery