Skip to content

Instantly share code, notes, and snippets.

@Exlord
Last active August 29, 2015 14:23
Show Gist options
  • Save Exlord/ec47d2515d393b7941a3 to your computer and use it in GitHub Desktop.
Save Exlord/ec47d2515d393b7941a3 to your computer and use it in GitHub Desktop.
Dynamicly loading stylesheets with js and handling stylesheets onload event
//Its very tricky to load LINK tags dynamicly and listen to their onload event, i found lots of hacks and tricks.
//This is the best and cleanest option that i came up with
//Basicly you just load the link file with ajax and put it inside a STYLE tag.
//This is a pure JS solution, no jQuery
function createXMLHTTPObject() {
var XMLHttpFactories = [
function () {return new XMLHttpRequest()},
function () {return new ActiveXObject("Msxml2.XMLHTTP")},
function () {return new ActiveXObject("Msxml3.XMLHTTP")},
function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];
var xmlhttp = false;
for (var i = 0; i < XMLHttpFactories.length; i++) {
try {
xmlhttp = XMLHttpFactories[i]();
}
catch (e) {
continue;
}
break;
}
return xmlhttp;
}
function sendRequest(url, callback, postData) {
var req = createXMLHTTPObject();
if (!req) return;
var method = (postData) ? "POST" : "GET";
req.open(method, url, true);
req.setRequestHeader("X-Requested-With", "XMLHttpRequest");
req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
if (postData)
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = function () {
if (req.readyState != 4) return;
if (req.status != 200 && req.status != 304) {
// alert('HTTP error ' + req.status);
return;
}
callback(req);
};
if (req.readyState == 4) return;
req.send(postData);
}
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
//This is the important part
sendRequest(url, function (request) {
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = response;
} else {
style.appendChild(document.createTextNode(response));
}
insertAfter(style, oreiginalLinkElement);
//or
document.getElementsByName('head')[0].appendChild(style);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment