Add CSS with javascript

1

JS

<script>
var estilos  = ["https://www.mexicodestinos.com/Content/StyleMD/a-hotels-md/general.min.css?1.0.8","https://www.mexicodestinos.com/Content/plugings/slick-1.5.7/slick/slick.min.css",
"https://www.mexicodestinos.com/Content/css/statica/general.min.css?1.0.0.7","https://www.mexicodestinos.com/Content/StyleMD/a-hotels-md/general.min.css?1.0.8"];
var tamanioEstilos = estilos.length;
var TamanioEstilosHtml  = document.styleSheets.length;
var bandera=0;
for(i=0;i<tamanioEstilos;i++)
{
for(y=0;y<TamanioEstilosHtml;y++){
if(estilos[i] != document.styleSheets[y].href){bandera=1;}
}
if(bandera==1){
document.getElementsByTagName("head")[0].append("<link href='"+estilos[i]+"' rel='stylesheet'>");
console.log("sepuso"+ y);
}bandera=0;
}
</script>

How do I add the link that is needed, this way, it is not added, it is for a widget

    
asked by Ernesto Emmanuel Yah Lopez 11.07.2017 в 23:24
source

1 answer

2

You can validate it by checking the property href of the array elements:

document.styleSheets

Example

function addcss () {
    var url = "<url del css>";
    for (var i = 0; i < document.styleSheets.length; i++ ) {
        if ( document.styleSheets[i].href === url) return;
    }

    var csslink = document.createElement("link");
    csslink.rel = "stylesheet";
    csslink.type = "text/css";
    csslink.href = url;
    document.getElementsByTagName("head")[0].appendChild(csslink);
}  
    
answered by 11.07.2017 / 23:41
source