Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a css/js resource is included in head

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

like image 611
Shai UI Avatar asked Dec 01 '22 22:12

Shai UI


2 Answers

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.

like image 154
Alex Turpin Avatar answered Dec 10 '22 12:12

Alex Turpin


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.

like image 27
Rob Himself Avatar answered Dec 10 '22 12:12

Rob Himself