0

I have a question about inserting html with JavaScript into the DOM after an Ajax call using JQuery's .load().

Assume the following sample html section:

<script>$(document).ready(function(){var e = $('#'+'@Servergenerated');})</script>

<div id='@Servergenerated'>Test Element</div>

If I return the above section through an Ajax call and insert the result into the DOM using JQuery's load() function -- Will both the markup rendering and the script execute as a blocking call? Meaning, since .load() executes on the single thread available to JavaScript, will it ensure that both the markup rendering and the JavaScript execution will finish before other JavaScript on the same main page can be invoked ?

The Ajax request is initiated through $("#someElement").load(..)

In the above case, can I always assume that the JS is always paired up with the correct html (so that the JS will execute against the ID that is currently defined on the page)

However, is there a difference between using .load() and .html().

Typically I use $.get to retrieve the data and then insert it into the DOM using .html(). This code is however in a third party library and it's uisng .load() instead..

4

1 回答 1

1

当您使用$().load(url,fn)时,该行后面的代码将在 html 附加到页面之前执行,因为$().load(url,fn)执行异步 http 请求来获取内容。见最后的例子。

要记住的另一件重要的事情是$().load(url,fn),如果返回的 html 包含 javascript,则该 javascript 可能会在页面上存在内容之前执行,从而导致插件无法正确初始化。这就是为什么强烈建议您不要使用$().load(url,fn)引入包含脚本的内容。

例子:

console.log(1)
$("#div1").load("page1.html",function(){
    console.log("4 maybe 5")
});
console.log(2)
$("#div2").load("page2.html",function(){
    console.log("5 maybe 4")
});
console.log(3)

在上面的示例中,日志 1 2 和 3 保证按此顺序发生,但是 4 和 5 可能会交换位置,具体取决于哪个 ajax 请求完成速度最快。除了不使用$().load(url,fn)或请求 div2 的内容成功请求 div1 的内容之外,没有其他方法可以避免。

于 2013-02-04T21:51:28.233 回答