问题描述
前提:我找到了这两个答案,但我不明白如何将其严格地应用于许多图书馆:
Premise: I've found these two answers but I don't understand how I can sistematically apply it for many libraries:
我有一个Augular 1.x应用程序,它依赖于几个库,其中许多库托管在CDN或外部服务器上.不幸的是,当用户处于脱机状态,Internet连接无法正常运行或出现(CDN)服务器问题时,某些库有时会无法下载并因此无法加载.
I've an Augular 1.x application which depends on several libraries, many of them hosted on CDN or external server.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.
在这种情况下,我想向用户显示出现错误.请重新加载或稍后再试"之类的视图.
In this case I want to show the the user a view like "there was an error. Please reload or try later".
我的疑问是:鉴于该库是通过以下方式简单地加载到 index.html 中的(一些甚至是异步)它们: >
My doubts is: Given that the library are simply loaded (some of them even asynchronously) in index.html by:
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/angular_material/0.8.2/angular material.min.css">
css (在头以内)和
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.min.js"></script>
用于 JS (在正文的末尾)
如何检测甚至一个库的下载失败?? (实际上,由于连接错误,它无法加载Angular,因此整个应用程序将无法运行.但是我有几个强制性库)
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)
还是我应该优先考虑可靠性(即在本地加载库)而不是性能(即缓存的CDN)?另外,我认为精确确定某些库(例如Google Apis)不能真正下载或通过Bower安装
Or should I give priority to reliability(i.e. loading libraries locally) over performance (i.e. cached CDN)?Also, I think it's important to precise that some libraries (e.g. Google Apis) can't really be downloaded or installed via Bower.
推荐答案
只需在标签中添加onerror处理程序即可.这可以称为后备,向用户发送消息等.
Just add an onerror handler to the tag. This can call a fallback, give the user a message etc.
使用不存在的网址会在此处弹出警报:
Using a non-existing url will here pop up an alert:
<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"
>
这篇关于如何检测一个或多个JS/CSS库何时无法加载(例如CDN)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!