如果加载 DOM 时未找到 javascript 库,如何动态更改它?
我有一个 HTML 页面,它使用“script”标签调用一些 javascript 库。
其中一个实际上是由另一台服务器提供的,该服务器偶尔会崩溃并因此报告“STATUS 404 NOT FOUND”。
使用此服务器的优点是它比我的更快,并且在大约 200 毫秒内加载库,而在我的服务器上则需要大约 2 秒。但是,我想在我的服务器上保留一个副本,并且仅在浏览器报告状态 404 时才加载它。
但是如何在 javascript 中对其进行编程呢?
function LoadLib(){
if (server status == 404)
{load library 1}
else
{load library 2}
}
类似的事情吗?
以前有人这样做过吗?
I have an HTML page which calls a few javascript libraries using the "script" tag.
One of these is actually provided by another server which occasionally crashes and thus reports a "STATUS 404 NOT FOUND".
The advantage of using this server is that it is faster than mine and loads the libary in about 200 miliseconds whereas when it is on my server is takes about 2 seconds. However, I would like to keep a copy on my server and only load it when the browser reports a Status 404.
But how do I program that in javascript?
function LoadLib(){
if (server status == 404)
{load library 1}
else
{load library 2}
}
Something along these lines?
Anyone done this before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这篇 CDN 托管 jQuery 的后备 帖子写得不错解决方案。
此示例使用 jQuery Microsoft CDN,因此请根据您的脚本更改
src
属性和对象检测。它还假设您正在加载的脚本创建了一些全局变量,您可以检查其是否存在以确保它已加载并运行。
注意:这不是唯一的选择。您还可以执行 AJAX 请求并读取其响应,但这是比上述解决方案更复杂的代码。
This Fallback for CDN hosted jQuery post had a decent solution.
This example uses jQuery Microsoft CDNs, so change the
src
attributes and the object detection as appropriate for your script.It also assumes the script you are loading creates some global variable you can check for existence to make sure it loaded and ran.
Note: This isn't the only option. You could also perform an AJAX request and read it's response, but that is more complicated code then the above solution.