最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to detect when asynchronously loaded jquery has finished loading? - Stack Overflow

programmeradmin1浏览0评论

I want to load jquery asynchronously on a page and then load an other script which depends on jquery (it executes jquery code when loaded). But how can I detect if jquery has finished lodading. Is there an event for this in jquery which fires when the library finished loading?

In theory I could load jquery like this:

<script async src="jquery.js" onload="jqueryloaded()"></script>

but I want the code to work on older browsers too which may not support the async and onload attributes. (In this case jquery is loaded synchronously.) That's why I'm looking for an event which jquery emits when it's loaded. Is there one?

I want to load jquery asynchronously on a page and then load an other script which depends on jquery (it executes jquery code when loaded). But how can I detect if jquery has finished lodading. Is there an event for this in jquery which fires when the library finished loading?

In theory I could load jquery like this:

<script async src="jquery.js" onload="jqueryloaded()"></script>

but I want the code to work on older browsers too which may not support the async and onload attributes. (In this case jquery is loaded synchronously.) That's why I'm looking for an event which jquery emits when it's loaded. Is there one?

Share Improve this question asked Mar 6, 2014 at 16:16 TomTom 7,5868 gold badges42 silver badges58 bronze badges 11
  • 3 I'm not understanding. For browsers that load it synchronously, it'll be done loading after the tag, so you could just put another script below it, and have it check to see if window.jQuery is present. <script>if (window.jQuery) jqueryloaded();</script> Otherwise, don't use <script async if you need to support all browsers. – cookie monster Commented Mar 6, 2014 at 16:20
  • @cookiemonster your comment would made a good answer... – A. Wolff Commented Mar 6, 2014 at 16:22
  • possible duplicate of Load javascript async, then check DOM loaded before executing callback – Deepak Ingole Commented Mar 6, 2014 at 16:23
  • 1 @Tom: Isn't your onload handler a single solution that works for both async/sync situations? The event should fire either way, right? – cookie monster Commented Mar 6, 2014 at 16:47
  • 2 @Tom: I think you may be right. Seems like there are some old IE issues with script.onload support. – cookie monster Commented Mar 6, 2014 at 16:55
 |  Show 6 more comments

2 Answers 2

Reset to default 16

You can try this:

var script = document.createElement('script');
script.src = 'jquery.js';
script.onload = jqueryloaded; // thx @Cookie_Monster
document.body.appendChild(script);

Have you seen http://headjs.com/?. An example it's:

head.load("jQuery.js", function() {
 // Call a function when done
 console.log("Done loading jQuery");
});
发布评论

评论列表(0)

  1. 暂无评论