开发者

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

开发者 https://www.devze.com 2023-04-01 00:38 出处:网络
Two questions: Does jQuery.load() run after the content of <script> is completely downloaded? If in case, there is a <script> in the document that will inject another <script> dyna

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.j开发者_开发技巧s 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.

:)


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


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消