简体   繁体   English

如何检测一个或多个 JS/CSS 库何时无法加载(例如 CDN)?

[英]How to detect when one or more JS/CSS library fail to load (e.g. CDN)?

Premise : I've found these two answers but I don't understand how I can sistematically apply it for many libraries:前提:我找到了这两个答案,但我不明白如何将它系统地应用于许多图书馆:

Detect and log when external JavaScript or CSS resources fail to load 当外部 JavaScript 或 CSS 资源加载失败时检测并记录

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

I've an Augular 1.x application which depends on several libraries, many of them hosted on CDN or external server.我有一个 Augular 1.x 应用程序,它依赖于几个库,其中许多库托管在 CDN 或外部服务器上。 Unfortunately when the user is offline, the Internet connection doesn't work well or there is a (CDN) server problem, some libraries occasionally fail to download and hence to load.不幸的是,当用户处于离线状态时,Internet 连接无法正常工作或 (CDN) 服务器出现问题,某些库偶尔会无法下载并因此无法加载。

In this case I want to show the the user a view like "there was an error. Please reload or try later".在这种情况下,我想向用户显示“出现错误。请重新加载或稍后再试”之类的视图。

My doubts is: Given that the library are simply loaded ( some of them even asynchronously ) in index.html by:我的疑问是:鉴于该库只是通过以下方式在index.html 中加载(其中一些甚至是异步的):

<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.2/angular material.min.css">

for css (within head ) and对于css (在head内)和

<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>

for JS (at the end of body )对于JS (在body末尾)

How can I detect the down(loading) failure of even one single library ?如何检测单个库的下载(加载)失败 (in fact, let's say it fails to load Angular's because of connection error, the whole app won't work. but I've several mandatory libraries) (事实上​​,假设它由于连接错误而无法加载 Angular,整个应用程序将无法运行。但我有几个必需的库)

Or should I give priority to reliability (ie loading libraries locally) over performance (ie cached CDN)?或者我应该优先考虑可靠性(即在本地加载库)而不是性能(即缓存的 CDN)? Also, I think it's important to precise that some libraries (eg Google Apis) can't really be downloaded or installed via Bower.此外,我认为重要的是要明确某些库(例如 Google Apis)不能真正通过 Bower下载或安装。

Just add an onerror handler to the tag.只需向标签添加一个 onerror 处理程序。 This can call a fallback, give the user a message etc.这可以调用回退,给用户一条消息等。

Example例子

Using a non-existing url will here pop up an alert:使用不存在的 url 将在此处弹出警报:

 <link onerror="alert('woa, error')" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.2/angular material.min.cssx" >

For custom function, just define a script block in the header before the link tags so you can call a custom function:对于自定义函数,只需在链接标签之前的标题中定义一个脚本块,即可调用自定义函数:

 <script> function myFunction() {alert("whaaaa.."); /* or something more meaningful */} </script> <link onerror="myFunction()" rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.2/angular material.min.cssx" >

What makes most sense in this case, is a feature check.在这种情况下最有意义的是功能检查。 Test for the existence of JS objects or JS methods to find out if a JS library has been loaded and test for the existence of certain CSS rules to find out if a CSS file has been loaded.测试是否存在 JS 对象或 JS 方法以查看是否已加载 JS 库,并测试是否存在某些 CSS 规则以查看是否已加载 CSS 文件。

See this Fiddle for a demo.有关演示,请参阅此 Fiddle

See also below for the most relevant parts of the code.另请参阅下面的代码中最相关的部分。


How to find out whether a certain CSS rule exists :如何找出某个 CSS 规则是否存在:

window.CSSRuleExists = function(rule) {
    var sSheetList = document.styleSheets;
    for (var sSheet = 0; sSheet < sSheetList.length; sSheet++) {
        var ruleList = sSheetList[sSheet].cssRules;
        for (var item = 0; item < ruleList.length; item ++){
            if(ruleList[item].selectorText === rule) {
                return true;
            }
        }
    }
    return false;
}

How to find out whether a certain JS method exists :如何找出某个 JS 方法是否存在:

window.JSFunctionExists = function(method, parent) {
    parent = (typeof parent === typeof undefined) ? window : parent;
    return (typeof parent[method] === 'function');
}

How to find out whether a certain JS object exists :如何找出某个 JS 对象是否存在:

window.JSObjectExists = function(object, parent) {
    parent = (typeof parent === typeof undefined) ? window : parent;
    return (typeof parent[object] === 'object');
}

How to use these functions :如何使用这些功能:

function process() {
    el1.innerHTML = CSSRuleExists('button.special');
    el2.innerHTML = JSFunctionExists('CSSRuleList');
    el3.innerHTML = JSObjectExists('location');
}

based on the accepted answer .基于接受的答案 Just tested on Firefox, Edge (the new one), Chrome and Opera.刚刚在 Firefox、Edge(新的)、Chrome 和 Opera 上进行了测试。

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Home</title>

    <script>
        function CssOrScriptFallBack(el) {
            if (el instanceof HTMLScriptElement || el instanceof HTMLLinkElement) {
                let Url = el.getAttribute('data-fallback');
                if (Url) {
                    let attr = el instanceof HTMLScriptElement ? 'src' : 'href';
                    el.setAttribute(attr, Url);
                }
            }
        }
    </script>

    <link href='https://not-working-cdn/file-name.min.css' rel='stylesheet'  
          onerror='CssOrScriptFallBack(this)' 
          data-fallback='/css/file-name.min.css' /> 

</head>
<body>
    ...
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当页面超过一页时(例如第2页)突出显示当前页面的脚本 - Script to highlight the current page when there is more than one page (e.g. page 2) 如何在特定的JavaScript代码中加载外部HTML页面? 例如,在JS函数中 - How to load an external HTML page within a specific JavaScript code? E.g. Within a JS function 在跨不同文件分割文件(例如html,图像,css,js等)时,HTML和CSS是否应保留在同一域中 - When splitting files (e.g. html, images, css, js etc) accross different files, should HTML and CSS remain on the same domain CSS-如何在CSS中执行“一次性CSS表达”? (例如,IE的最大高度/最大宽度) - CSS - How to do a: “ONE-TIME CSS EXPRESSION” in css? (e.g. max-height / max-width for IE) 如何在 Google Forms 上使用编程逻辑(例如 JS)? - How to use programming logic (e.g. JS) on Google Forms? 从json文件输出多个屏幕截图(例如iTunes搜索api)? - Output of more than one screenshots from json-file (e.g. itunes search api)? 在JavaScript中使用Mozilla的NSS库(例如WeaveCrypto.js) - Using Mozilla's NSS library in JavaScript (e.g. WeaveCrypto.js) 通过 ES6 模块导入加载和使用遗留 JS 模块(例如 IIFE) - Load and consume legacy JS modules (e.g. IIFEs) via ES6 module imports CSS / JS中导航菜单中的箭头(例如playframework.org) - Arrow in nav menus in CSS/JS (e.g. playframework.org) 检测滚动条是否可见(例如在移动设备上) - Detect if scrollbar is visible (e.g. on a mobile device)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM