Dynamically load external css link

Asked

Viewed 37 times

0

I have 2 external CSS files that contain page backgrounds.

In 1 only have links to images . webp and in other only . PNG , I am using a script to detect if the browser accepts . webp and if so it changes the external CSS link in HEAD for external css with . webp, by default it initially points to . png, tested on a page simpler and gave ok, but at the time to put where I want not worked, follow the code:

At the head:

<link href="‪arquivos_css/png.css" rel="stylesheet" id="key">

In the JS:

//////////////////////////////////////////////////////////////
// FUNÇÃO QUE CRIA O LINK EXTERNO CSS PARA INSERIR NO HEAD  //     OK//
//////////////////////////////////////////////////////////////  
    function loadCSS(url){
        var link = document.createElement('link');
        link.setAttribute('href', url );
        link.setAttribute('rel', "stylesheet" );
        link.setAttribute('id', "key" );

        var para  = document.getElementsByTagName('head')[0]; //Nó pai HEAD
        var velho = document.getElementById('key');        //local exato do elemento a ser substituido

        para.replaceChild(link, velho);                      //Substituímos o velho pelo novo(link)
    }
//////////////////////////////
Chamada à função do webP
/////////////////////////////

WebpIsSupported(function(isSupported){
    if(isSupported){
       //CHAMA A FUNÇÃO LOADCSS e carrega o link CSS externo com WEBP
       loadCSS('arquivos_css/webp.css');
    }
}); 
//////////////////////////////////////////////////////////////  
// FUNÇÃO QUE DETECTA A COMPATIBILIDADE DO BROWSER COM WEBP // 
//////////////////////////////////////////////////////////////
function WebpIsSupported(callback){
    if(!window.createImageBitmap){
        callback(false);
        return;
    }
    var webpdata = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoCAAEAAQAcJaQAA3AA/v3AgAA=';
    fetch(webpdata).then(function(response){
        return response.blob();
    }).then(function(blob){
        createImageBitmap(blob).then(function(){
            callback(true);
        }, function(){
            callback(false);
        });
    });
}   

The mistake you’re making on Chrome is this: Failed to load Resource: net:ERR_FILE_NOT_FOUND

Who can help I thank you in advance !!

  • net:ERR_FILE_NOT_FOUND That means the file was not found, see if in the function loadCSS('arquivos_css/webp.css'); if you put loadCSS('/arquivos_css/webp.css'); to fetch the file at the root...

  • Hello Daniel, I tried and nothing, same thing, until the root url c:/system/etc I tried and nothing.

  • I go to Elements and is there in HEAD but the files do not load and gives this error on the console.

  • Anyone can help ?

  • On the console should be showing which way he is looking for the file, take a look to see if this file is really there

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.