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

删除回忆录丶 提交于 2019-12-11 01:17:24

问题


Two questions:

  1. Does jQuery.load() run after the content of <script> is completely downloaded?

  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?

Thanks


The example for the 2) question is like that:

<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. in which myscript2.js include the function myscript2.functionA

Obviously, I want to run myscript2.functionA after myscript2.js is loaded completely.

:)


回答1:


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). 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.

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();



回答2:


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. You should consider this standard practice. The solution is simple:

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


来源:https://stackoverflow.com/questions/7247207/does-jquery-load-load-after-script-content-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!