简体   繁体   English

jQuery.load()是否在加载后<script> content is loaded?

[英]Does jQuery.load() load after <script> content is loaded?

Two questions: 两个问题:

  1. Does jQuery.load() run after the content of <script> is completely downloaded? jQuery.load()是否在完全下载<script>的内容后运行?

  2. If in case, there is a <script> in the document that will inject another <script> dynamically, does load() run after after the content of the 2nd script is downloaded or it will run after the original, non-dynamic content is loaded? 如果以防万一,文档中有一个<script>将动态注入另一个<script> ,则在下载第二个脚本的内容之后, load()会运行还是在原始的非动态内容被下载后运行?装?

Thanks 谢谢


The example for the 2) question is like that: 2)问题的示例如下:

<html>
<head>
<script src="myscrip1.js"></script>
<script>
$(document).load( myscript2.functionA );
</script>
</head>
</html>

Where myscript.js will inject myscript2.js into the dom. myscript.js将myscript2.js注入dom的位置。 in which myscript2.js include the function myscript2.functionA 其中myscript2.js包含函数myscript2.functionA

Obviously, I want to run myscript2.functionA after myscript2.js is loaded completely. 显然,我想在myscript2.js完全加载后运行myscript2.functionA。

:) :)

The document ready event is fired when all of the resources referenced in the initial HTML have been downloaded (or timed out in case there are errors). 当初始HTML中引用的所有资源均已下载(或在出现错误时超时)时,将触发文档就绪事件。 If you dynamically inject a reference to another script (like the facebook api, google analytics, etc) it's readiness is undefined with relation to the document ready event. 如果您动态注入对另一个脚本的引用(例如facebook api,google Analytics等),则相对于文档就绪事件而言,其准备状态是不确定的。

If you want to check that your external script is ready you can check that an object that it creates has been loaded . 如果要检查外部脚本是否准备就绪,可以检查其创建的对象是否已加载

<script type="text/javascript">
  var startAfterJqueryLoaded = function(){
    if(typeof jQuery === "undefined" ) {
        setTimeout( startAfterJqueryLoaded, 100 );
        return;
    }

    // jQuery is ready, do something
  }

  startAfterJqueryLoaded();

</script> 

Or if you have control of the script you are dynamically injecting you can establish a global function that it will call when it's ready. 或者,如果您控制着要动态注入的脚本,则可以建立一个全局函数,准备好后将调用它。

<script type="text/javascript">
  window.dynamicScriptIsReady = function(){
    // do something
  }
</script> 


// Dynamic.js
// ...Setup whatever

window.dynamicScriptIsReady();

If you put the load event handler within the standard document ready event handler wrapper, it will ensure that the external script is loaded first. 如果将load事件处理程序放入标准document ready事件处理程序包装器中,它将确保首先加载外部脚本。 You should consider this standard practice. 您应该考虑这种标准做法。 The solution is simple: 解决方案很简单:

<script src="myscrip1.js"></script>
<script>
$(document).ready(function() {
  $(document).load( myscript2.functionA );
});
</script>

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

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