63
rated 0 times
[
69]
[
6]
/ answers: 1 / hits: 66633
/ 14 Years ago, tue, january 18, 2011, 12:00:00
I need to check (in Javascript) if a CSS file is loaded and if not then to load it. jQuery is fine.
More From » jquery
I need to check (in Javascript) if a CSS file is loaded and if not then to load it. jQuery is fine.
Just check to see if a <link>
element exists with the href
attribute set to your CSS file's URL:
if (!$(link[href='/path/to.css']).length)
$('<link href=/path/to.css rel=stylesheet>').appendTo(head);
The plain ol' JS method is simple too, using the document.styleSheets collection:
function loadCSSIfNotAlreadyLoadedForSomeReason () {
var ss = document.styleSheets;
for (var i = 0, max = ss.length; i < max; i++) {
if (ss[i].href == /path/to.css)
return;
}
var link = document.createElement(link);
link.rel = stylesheet;
link.href = /path/to.css;
document.getElementsByTagName(head)[0].appendChild(link);
}
loadCSSIfNotAlreadyLoadedForSomeReason();