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

6

It's not a problem, but a question that can solve many of my problems.

Let's say I upload this CSS file to my site:

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

But if host-1.com is offline? Is there any way to check this and use another file, for example:

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

As if I meant it like this for 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'/>
    
asked by anonymous 07.01.2017 / 20:41

3 answers

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 on will overlap) with the other case the content is different. If it is not, the browser will use the last one declared.

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

    
07.01.2017 / 20:45
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 should contain the alternate CSS address.

Another way, perhaps has several fallbacks, also using JavaScript would be dynamically creating the element and testing with onerror . The function would be loadCssFallback(<array com endereços css> [, <log>]); , thus:

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

Complete 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);
    
07.01.2017 / 21:27
2

Purely with html and css, I do not know any method of doing this comparison. But if you use a server language, such as php, you can get what you want.

First step would be to delegate to php the include of your css as follows:

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

In this file css-handler.php you will need to do the css include, but you will have tools to make your desired conditional. This conditional you can do if using 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-mouth, just to illustrate the idea itself, but it works. You can improve it better if it is needed.

    
07.01.2017 / 21:41