Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
1

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();

[#94173] Monday, January 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
muhammadbrandend

Total Points: 670
Total Questions: 95
Total Answers: 97

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;