简体   繁体   English

jQuery使用$ {document)加载外部JavaScript.ready失败

[英]jQuery load external JavaScript with $(document).ready fails

I would like to load an external HTML. 我想加载外部HTML。 In addition, the external HTML contains some JavaScript code. 此外,外部HTML包含一些JavaScript代码。 Since the load function does not load this script, I have to use getScript: 由于加载功能不会加载此脚本,因此我必须使用getScript:

<div id="external-content"></div>

<script type="text/javascript">
  $("#external-content").load("external.html #myid", function() {
    // do something
  });
  $.getScript("external.js");
</script>

That works like a charm unless the external.js has a $(document).ready command, which tries to access elements from external.html. 除非external.js具有$(document).ready命令,该命令试图从external.html访问元素,否则它的工作原理就像一种魅力。 It seems to me, that the event is fired too early. 在我看来,该事件触发得太早了。 I also tried to put the command $.getScript("external.js"); 我还尝试放置命令$ .getScript(“ external.js”);。 into the .load callback, but did not succeed. 进入.load回调,但未成功。 Note that sing external.html separately and including the external.js directly works like expected. 请注意,单独唱external.html并包含external.js可以像预期的那样直接工作。

Unfortunately, the timing of this makes sense (ie. this is correct behaviour). 不幸的是,这样做的时机很合理(即,这是正确的行为)。 The script inside the tag fires up a retrieval of external.html and does not wait for it to return, it keeps moving on to the retrieval of external.js. 标记内的脚本会触发对external.html的检索,并且不等待其返回,而是继续进行对external.js的检索。 In the meantime, the 'base' document is still loading and may (in fact probably) will complete before externa.html is retrieved. 同时,“基本”文档仍在加载中,并且可能(实际上可能)将在检索externa.html之前完成。

So, you can run into a timing situation whereby: 因此,您可能会遇到以下情况:

Document is indeed ready (external.html being loaded is not a condition of the DOM being scriptable), external.js is loaded and available, but external.html hasn't been fully loaded yet. 文档确实已经准备好了(external.html的加载不是DOM可编写脚本的条件),external.js已加载且可用,但是external.html尚未完全加载。 The document ready function will fire (because the document IS ready!) before the elements of external.html are present. 文档就绪功能将在存在external.html元素之前触发(因为文档已就绪!)。

If you want to continue this approach, there are probably ways to rejig it such that you are using on() inside external.js to delegate to a listener to the base document (#myid) for events on elements inside external.html. 如果要继续使用此方法,则可能有一些方法可以对其进行重新调整,以使您可以在external.js中使用on()将侦听器委派给基础文档(#myid)的侦听器,以获取有关external.html中元素的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM