加载 DOM 后如何运行 jQuery 的后备副本?
以下是我文档中 body
结束标记上方 标记中的第一行代码(它指定本地提供的 jQuery 副本是在 Google 的 CDN 失败的情况下运行):
if(!window.jQuery){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/jquery.js';
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
jQuery(document).ready(function($){
// page behaviors
});
它确实执行成功,因为如果我的计算机未连接到 Internet(这是本地提供的页面),则会插入 jQuery 的本地副本。但是,下面的 document.ready()
部分不会执行。我猜这是因为它是在 jQuery 的后备副本生效之前调用的。以某种方式“延迟”其执行以便 jQuery 的任一副本都能正常工作的正确做法是什么?
The following are the first lines of code in a <script>
tag just above the closing body
tag in my document (it specifies that a locally-served copy of jQuery is run in the event that Google's CDN fails):
if(!window.jQuery){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/jquery.js';
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
jQuery(document).ready(function($){
// page behaviors
});
It does execute successfully, in the sense that if my computer is not connected to the Internet (this is a locally-served page), the local copy of jQuery is inserted. However, the document.ready()
section below does not execute. I'm guessing this is because it is invoked before the fallback copy of jQuery takes effect. What's the proper practice for somehow "delaying" its execution so that either copy of jQuery will work properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
在调用 jQuery
之前,您需要确保附加到 dom 的脚本已完成加载。您可以使用此处描述的技术来完成此操作:
if(!window.jQuery){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/js/jquery.js';
script.onreadystatechange= function () {
if (this.readyState == 'complete') jQueryLoaded();
}
script.onload = jQueryLoaded;
var scriptHook = document.getElementsByTagName('script')[0];
scriptHook.parentNode.insertBefore(script, scriptHook);
}
function jQueryLoaded() { };
您还可以将 jQuery 内容作为 Ajax 请求获取,创建一个脚本标签,将其作为脚本的主体并附加它。那也行。
php 解决方案将是这样的:
$google_jquery = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
$fp = @fsockopen($google_jquery, 'r');
if (!$fp)
{
echo '<script type="text/javascript" src="js/jquery.js"></script>';
}
else
{
echo '<script src="'.$google_jquery.'"></script>' }
}
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
考虑使用现有的脚本加载器,例如 yepnope。主页上有一个示例说明了您正在尝试执行的操作。
Consider using an existing script loader such as yepnope. There's an example of exactly what you're trying to do on the home page.