Is it possible to load alternative . css links in case the primary link is not working?

Asked

Viewed 218 times

6

Not really a problem, but a question that can solve several of my problems.

Let’s say I upload this CSS file to my website:

<link href='http://host-1.com/style.css' rel='stylesheet' type='text/css'/>

But if the host-1.com off the air? Is there any way to check this and use another file, example:

<link href='http://host-2.com/style.css' rel='stylesheet' type='text/css'/>

As if I meant to say so to my code:

//Carregar esse arquivo css
<link href='http://host-1.com/style.css' rel='stylesheet' type='text/css'/>
//Mas no caso dele não funcionar, carregue esse:
<link href='http://host-2.com/style.css' rel='stylesheet' type='text/css'/>
  • If it is a "mirror" you can include both, however, it will force the user to download both files when both are working.

  • 1

    If the CSS is WELL lean, and its load is so important, you can place it inline on the page (in a <style> block), ensuring it is always present. You just have to understand the cost of this: it doesn’t take advantage of caching on different pages, it will be loaded every time, and give a little more maintenance work (but not as much as they say). It’s not normal, but if the situation requires it, it’s not wrong how people exaggerate around.

  • @Bacco to tell you the truth, it takes a little older sites for maintenance and this is well used if Naum the most.. kkkk

3 answers

8

In pure HTML is not possible, but if you use Javascript you can do something like:

function loadCssFallback(el)
{
    var url = el.getAttribute("data-fallback");
  
    console.log("Carregando fallback:", url);
  
    el.onerror = null;
    el.href = url;
}
<link rel="stylesheet"
      type="text/css"
      href="normal.css"
      onerror="loadCssFallback(this)"
      data-fallback="fallback.css"
>

Note that I create an attribute called data-fallback, it must contain the alternative CSS address.

Another way, if you have several fallbacks, also using Javascript would be to dynamically create the element and test with onerror. The function would look like this loadCssFallback(<array com endereços css> [, <log>]);, being like this:

  • loadCssFallback([ "//cdn.site.com/fallback.css", "css1.css" ]); no console log
  • loadCssFallback([ "//cdn.site.com/fallback.css", "css1.css" ], true); displays the log in the console

Full example:

function loadCssFallback(urls, log)
{
    var link, current = 0;

    function done()
    {
        if (log && console) {
            console.log("Loaded", link.href);
        }

        link.onload = link.onerror = null;
    }

    function trigger()
    {
        if (log && console) {
            console.log("Iniciou...");
        }

        tryNext();
    }

    function tryNext()
    {
        current++;

        if (!urls[current]) {
             console.log("Nenhum CSS carregou");
             return;
        }

        loadCss(urls[current]);
    }

    function loadCss(url)
    {
        if (log && console) {
            console.log("Carregando CSS", current, urls[current]);
        }

        link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";

        link.onerror = tryNext;

        link.onload = done;

        link.href = url;

        document.head.appendChild(link);
    }

    //Verifica se a página já foi carregada
    if (/^(interactive|complete)$/i.test(document.readyState)) {
        trigger();
    } else {
        document.addEventListener('DOMContentLoaded', trigger);
    }
}

var meusCSSs = [
    "cssprincipal.css",
    "fallback1.css",
    "fallback2.css",
    "fallback3.css",
    "https://cdn.sstatic.net/Sites/br/all.css?v=a482a814f698"
];

loadCssFallback(meusCSSs, true);

  • In case js is disabled as it does ?

  • @Magichat I believe that virtually all sites made in the last years use JS and if you have JS offline and will cause other problems and this will be just one more, ie not use Javascript on today is almost the same as having a general blackout, causing the main means of transport to stop.

  • I agree, but in my view, there is the possibility to offer 1 more option, using html.

4


Yes, just declare them within the tag head.

An example would be:

<head>
    <link href='http://host-1.com/style.css' rel='stylesheet' type='text/css'/>
    <link href='http://host-2.com/style.css' rel='stylesheet' type='text/css'/>
</head>

What will happen is that the 2 will be loaded and 1 will conflict (but will load, what will conflict is the internal CSS of both and depending will overlap) with the other if the content is different. If not, the browser will use the last declared.

To make a check if there was a problem of loading a specific file before using it, you will need a programming language itself, which is absent in your tags.

  • I could inform the cause of the negative, where is the problem in my answer ?

  • I’m not the one who tested negative '-'

  • 1

    You did not answer the question. A conditional was requested to load the second option, when the first failure, in my understanding.

  • But answer me one thing, example, you said I can declare them in the tag head, if I declare both, won’t it get too heavy for the user? Kind of keep loading two files? Or give some error, since I also want to do this with files. js?

  • 1

    Remembering that when you do not have a complete answer, however you have a valuable tip, or something that can help, it is possible to comment on the question.

  • @mauhumor makes a conditional for this with css and html for me to see...

  • 1

    And I happened to answer the question?

  • @mauhumor not but I do, if you read the answer carefully you will see that you are drawing the wrong attention...

  • 1

    If I don’t have the answer to the problem, I simply don’t create an answer. That’s why I voted negative.

  • First your answer has been edited. Second, it doesn’t say how to do this. "But what if the host-1.com is off the air? There is some way to check this and use another file, example:". The correct answer to this question is a simple one. No. And maybe a tip to load the files, like the one you gave, only for me would look better in a comment.

  • @If it will get heavy or does not depend on the size of the files, to make so that only the necessary file is loaded, need to use a language like php, which is missing in the tag, but my answer answers exactly the question

  • 1

    Yes, I judge my nick. If I’m wrong, others have annulled my negative vote.

  • hehe gets like this Naum, I’ve watched you think you a nice guy @mauhumor

Show 9 more comments

2

Purely with html and css, I don’t know any method of making this comparison. But if you use a server language like php, you can get what you want.

First step would be to delegate php to include your css in the following way:

<link href='css-handler.php' rel='stylesheet' type='text/css'/>

in that file css-handler.php you will need to do the include of css, but you will have tools to make your desired conditional. This condition you can do using the Curl:

<?php

function verifyIdCssExists($css) {
    // Verificar local 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $css);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Se achou, beleza, usa ele
    if($code == '200')
        die($data);
}

$cssOptions = [
    'http://host-1.com/style.css',
    'http://host-2.com/style.css',
    'http://host-3.com/style.css',
];

foreach($cssOptions as $cssLink)
    verifyIdCssExists($cssLink);

This code is super half-full, just to illustrate the idea even, but it works. You can improve it better if you need.

  • 1

    PS: I liked having done with PHP, although I think Guilherme’s solution better, I improved the code for you.

Browser other questions tagged

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