我在从 CDN 加载 Bootstrap + jquery 时遇到问题,有时它无法从 CDN 加载/导入 例如:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
它在打开时不会加载到站点中。 我想要做的是在我的服务器中也添加相同的文件,所以如果它无法从谷歌服务器上传这个文件,它会从我的服务器加载它。 例如:
<link rel="stylesheet" href="#mydomain#/css/bootstrap.min.css">
如果从 CDN 成功加载它,我如何才能以不会加载两次的方式执行上述操作(有没有办法这样做或更好的方法来实现这一点?)提前致谢
最佳答案
这段代码将处理脚本加载失败,并允许您添加将加载的回退属性...
var scripts = document.querySelectorAll("script[data-fallback]");
[].forEach.call(scripts, function(script) {
var listener = script.addEventListener("error", function() {
var newScript = document.createElement("script");
newScript.setAttribute("src", script.getAttribute("data-fallback"));
document.querySelector("head").appendChild(newScript);
});
});
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.fail"
data-fallback="https://something-local.com/jquery.js"></script>
注意:这在此页面上不起作用。这只是 Stack Overflow 片段的本质。这是一个有效的 jsfiddle 演示......
http://jsfiddle.net/ArchersFiddle/pbfv6q4x/
如果您在该页面上打开控制台,您将看到原始脚本加载错误,然后显示后备脚本的输出已加载。
这是同样的事情,但是对于样式表...
var stylesheets = document.querySelectorAll("link[rel=stylesheet][data-fallback]");
[].forEach.call(stylesheets, function(stylesheet) {
var listener = script.addEventListener("error", function(e) {
var newStylesheet = document.createElement("link");
newStylesheet.setAttribute("rel", "stylesheet");
newStylesheet.setAttribute("href", stylesheet.getAttribute("data-fallback"));
document.querySelector("head").appendChild(stylesheet);
});
});
关于javascript - 如果加载失败,我如何在本地加载资源而不是 CDN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51926428/