Check if there is a css ref link before adding one

I am dynamically adding a .css file to the page. Does it matter if the .css file is already in the link? How can I check if a link exists, I was thinking of checking in my head using javascript. This is how I add the class:

<script type="text/javascript">
(function(){
    var AppendNewStyle = document.createElement("link");
    AppendNewStyle.setAttribute("href", "/Content/Extras.css");
    AppendNewStyle.setAttribute("rel", "stylesheet");
    AppendNewStyle.setAttribute("type", "text/css");
    $('head')[0].appendChild(AppendNewStyle);
})();
</script>

Can I check here to find out if the file is in my head or I just don't need to worry about having two connected?

+3
source share
3 answers

You should be able to query for those link elements like any other element. Since you are using jQuery:

var allLinks = $("link");

Alternatively, you can use the attribute selector to find the link you need:

var myLink = $('link[href="' + url +'"]');  //Find the link that matches your URL

script, , , .


2017-04 :

yummier!

var myLink = $(`link[href="${url}"]`)

JQuery:

var myLinks = document.querySelectorAll(`link[href="${url}"]`)
+4

load error . , .

CSS - AJAX, AJAX AJAX.


, URL- CSS.

var links = document.getElementsByTagName('link'),
    linksLen = links.length,
    i;

for(i=0;i<linksLen;i++){
    if(links[i].href.indexOf(urlToLoad) !== -1){
        //found
    }
}
+5

, css . , , ID css

 var cssSelector = document.getElementById("uiCss");

    // Load UI CSS file
    if (!cssSelector) {
        var filename = 'http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css';
        var fileref = document.createElement("link");
        fileref.setAttribute("href", filename);
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("ID", "uiCss");
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
+1
source

All Articles