我的网站正在使用jquery.load()
在页面的一大块上进行导航。我真的很欣赏只包含加载内容的特定部分的能力,这里是 id="content"的 div:
$(frame_selector).load(url +" #content", function(response, status, xhr) {...});
但现在我需要能够运行作为动态加载页面一部分的脚本。 Jquery.load()
删除这些脚本,但是 jquery.ajax()
没有。所以我复制了 jquery.load
的部分内容功能在这样的 ajax 调用中:
$.ajax({
url: url,
dataType: 'html',
success: function(data, textStatus, XMLHttpRequest) {
// Only include the response within the #content id element.
$(frame_selector).html( jQuery("<div>")
.append(data)
.find("#content")
);
}
});
问题是从 ajax 调用动态加载的脚本运行不可靠。有时它们似乎没有任何效果,也许是因为它们运行得太早了。这些脚本只是在 jquery 中进行 DOM 操作——不依赖于图像或 flash 或任何不应该加载的东西。为了避免陷入困境,我使用了这个可怕的技巧来让事情正常运转。而不是仅使用 AJAX 加载的脚本:
$(document).ready( function() {...} ); // unreliable
我在运行之前将脚本延迟了 200 毫秒:
$(document).ready( window.setTimeout( function() {...}, 200 )); // HATE THIS
有人知道如何在不硬编码延迟的情况下可靠地完成这项工作吗?我猜这是 <script>
之间的竞争条件和我的逻辑加载 #content
到一个新的 div 中,但我不知道该怎么做。
最佳答案
我假设脚本正在对您通过 AJAX 添加的 DOM 元素进行操作。
jQuery 有一个 isReady
它设置一次 ready
的属性页面已触发事件。
任何后续调用 jQuery.ready(...)
首先会检查这个isReady
旗帜。如果该标志设置为 true,它将立即调用处理程序。您可以看到为什么这会导致您的代码出现问题。
一种选择是将响应加载到 jQuery 片段中并解析出所有 <script />
稍后执行的标记。
var ajaxResponse = $(html);
var scripts = ajaxResponse.find('script');
// Move your scripts into a new element
var tempScripts = $().append(scripts);
// Append your content, followed by your script tags
$(document).append(ajaxResponse);
$(document).append(tempScripts);
关于jquery - 在 jquery.ajax() 加载的页面中运行的脚本运行 document.ready 太早,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4073951/