<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script src="myscript.js"></script>
</head>
I'd like to have a function that checks if a resource is included in the head
checkIfHeaderHas('myscript.js'); // would return true
checkIfHeaderHas('mystyle.css'); // would return true
checkIfHeaderHas('mybla.css'); // would return false
But I'm wondering how I can go about searching the head for a filename? (in the 'src' if it's javascript, or in the 'href' if it's a css)
I made a small function that does what you want. It loops through all <link>
and <script>
elements until it finds a script with that name. If it doesn't, it returns false.
function checkIfIncluded(file) {
var links = document.getElementsByTagName("link");
for(var i = 0; i < links.length; i++) {
if (links[i].href.substr(-file.length) == file)
return true;
}
var scripts = document.getElementsByTagName("script");
for(var i = 0; i < scripts.length; i++) {
if (scripts[i].src.substr(-file.length) == file)
return true;
}
return false;
}
console.log(checkIfIncluded("mystyle.css"));
console.log(checkIfIncluded("myscript.js"));
console.log(checkIfIncluded("mybla.css"));
Live example
Note that this will not only find resources in the <head>
, but in thew whole document. If you really need to look inside the head, tell me and we'll figure something else.
If you're using jQuery you could maybe do something like:
var checkIfHeaderHas = function(fileName) {
// Start with CSS.
$.each($("header link"), function() {
if ($(this).attr("href").toLowerCase() === fileName.toLowerCase())
return true;
});
// Then JavaScript.
$.each($("header script"), function() {
if ($(this).attr("src").toLowerCase() === fileName.toLowerCase())
return true;
});
// Default response.
return false;
}
Apologies for anything that's not quite right. I'm knocking this out from my phone, and didn't have time to test.
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