HTML if语句在CDN失败时加载本地JS / CSS [英] HTML if statement to load local JS/CSS upon CDN failure

查看:154
本文介绍了HTML if语句在CDN失败时加载本地JS / CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从CDN或任何外部服务器加载CSS / JS文件时,由于外部故障,可能(即使概率很低)错过文件。在这种情况下,由于缺少适当的CSS和JS,html页面将被破坏。

When loading a CSS/JS file from CDN or any external server, it is possible (even with low probability) to miss the file due to external failure. In this case, the html page will be corrupted in the lack of appropriate CSS and JS.

是否有一种实用的方法在CDN失败时加载本地版本?

Is there a practical approach to load a local version upon CDN failure?

<link rel="stylesheet" href="http://cdn.com/style.css" type="text/css" />
IF (not loaded style.css){
<link rel="stylesheet" href="/css/style.css" type="text/css" media="screen" />
}

为JS做这个会更容易,因为我们可以测试JS函数(在JS文件中提供);然后,在失败时加载本地文件。例如,测试,如果jQuery库可用。

It would be easier to do this for JS, as we can test a JS function (provided in the JS file); then, loading the local file upon failure. For example, testing, if jQuery library is available.

但是,我很想知道是否有实用的方法!

However, I am curious to know if there is a practical method for this!

推荐答案

我会这样做。

在样式表中创建一个类 ui-helper-hidden 然后添加div作为页面上的第一个元素;

Create a class within your stylesheet ui-helper-hidden and then add a div as the first element on your page;

<body><div class="ui-helper-hidden"></div><!-- rest of html --></body>

检查完毕后确保已加载CDN javascript文件,然后使用这段代码注意我正在使用jquery

After you have checked to make sure your CDN javascript file has been loaded, then use this bit of code note i am using jquery

<script>
    // CSS Fallback
    $(function () {
        if ($('.ui-helper-hidden:first').is(':visible') === true) {
            $('<link rel="stylesheet" type="text/css" href="/pathtocss/nameofstylesheet.css" />').appendTo('head');
        }
    });
</script>

这将检查是否应该隐藏的元素。如果它不是隐藏的,那么你知道你的css文件没有从CDN加载。

This will check to see if the element which should be hidden is or not. If it isnt hidden, then you know your css file has not loaded from the CDN.

我将此方法用于 jQuery和jQuery UI通过CDN

这篇关于HTML if语句在CDN失败时加载本地JS / CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆