I'm trying to create a page theme function for my site. I want to load the corresponding themes dynamically on the page using separate CSS files.
I'm using this code:
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", 'link.css')
document.getElementsByTagName("head")[0].appendChild(fileref)
Which works fine, but it doesn't return any info if the CSS file has loaded or not.
Is there a way to catch when the .css
is loaded? Maybe by using ajax?
To load a . js or . css file dynamically, in a nutshell, it means using DOM methods to first create a swanky new " SCRIPT " or " LINK " element, assign it the appropriate attributes, and finally, use element. appendChild() to add the element to the desired location within the document tree.
Load CSS and JS files dynamically: We create a script element for the JS file and link element for the CSS file as required using DOM, assign the appropriate attributes to them, and then add the element to the desired location within the document tree using the element. append() method.
If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.
This is a collection of methods which give you the ability to query the stylesheets collection in a document, add and remove rules, and dynamically create new sheets.
Internet Explorer will trigger an onReadyStateChange
event when CSS file is loaded (or any other change in it's readyState
).
Other browsers do not trigger any event, so you will have to manually check if the stylesheet has been loaded, which is easily possible by checking the document.styleSheets
object at a fixed interval.
Example
window.onload = function (){
var filename = "link.css",sheet,i;
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", filename);
readyfunc = function () {
alert("File Loaded");
}
timerfunc = function (){
for (i=0;i<document.styleSheets.length;i++){
sheet = document.styleSheets[i].href;
if(sheet !== null && sheet.substr(sheet.length-filename.length) == filename)
return readyfunc();
}
setTimeout(timerfunc,50);
}
if (document.all){ //Uses onreadystatechange for Internet Explorer
fileref.attachEvent('onreadystatechange',function() {
if(fileref.readyState == 'complete' || fileref.readyState == 'loaded')
readyfunc();
});
} else { //Checks if the stylesheet has been loaded every 50 ms for others
setTimeout(timerfunc,50);
}
document.getElementsByTagName("head")[0].appendChild(fileref);
}
It's ugly, but it works in all browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With