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

javascript - How to execute a function when jQuery is loaded? - Stack Overflow

programmeradmin0浏览0评论

I'm making a bookmarklet and using jQuery for it (with noConflict). I need to wait for jQuery to load, to execute all the jQuery code.

I know I can check with typeof $ for jQuery, but I'm actually more looking for an event handler. Right now I'm just using setTimeout with a delay of 1s, because jQuery is proberly loaded then. I feel this is not a good solution. It's not clean code and relies on jQuery to load in 1s.

Is there any other way to afford this?

I'm making a bookmarklet and using jQuery for it (with noConflict). I need to wait for jQuery to load, to execute all the jQuery code.

I know I can check with typeof $ for jQuery, but I'm actually more looking for an event handler. Right now I'm just using setTimeout with a delay of 1s, because jQuery is proberly loaded then. I feel this is not a good solution. It's not clean code and relies on jQuery to load in 1s.

Is there any other way to afford this?

Share Improve this question asked Aug 15, 2011 at 13:13 js-coderjs-coder 8,34610 gold badges43 silver badges59 bronze badges 2
  • Are you dynamically appending jQuery to the DOM in the bookmarklet? – pimvdb Commented Aug 15, 2011 at 13:15
  • Yep. I'm doing that via appendChild. – js-coder Commented Aug 15, 2011 at 13:15
Add a ment  | 

5 Answers 5

Reset to default 5

Just for the records, pleteness and for those that didn't know: Without an event handler, a good alternative would be to poll for jQuery every X amount of time. Ex:

function is_jquery_here(){
    setTimeout(function(){
      if(window.jQuery){
         my_jquery_code_here();
      } else {
        is_jquery_here();
      }
    }, 300);
}
is_jquery_here();

Since you say you're appending it dynamically, you could make use of onload:

var elem = document.createElement('script');
elem.onload = function() {
    // script is loaded, you can now do things with jQuery
};
elem.src = 'path to jquery';
document.getElementsByTagName('head')[0].appendChild(elem);

Not every browser supports .onload for script elements, so if you need cross-browser patibility, use onreadystatechange as well:

function load( src, callback )
{
  var s,r;
  s = document.createElement('script');
  s.type = 'text/javascript';
  s.src = src;
  s.onload = s.onreadystatechange = function(){
    if ( !r && ( !this.readyState || this.readyState == 'plete' ) )
    {
      r = 1;
      callback();
    }
  };
  document.body.appendChild(s);
}

If you have jQuery script in the page and you just want to make sure its loaded first, then I'd highly remend that one

window.onload = function() {
  //.....your jquery code....
};

Michael is right. You could also use this shorthand

$(function() {
    // Code for on docload here
});
发布评论

评论列表(0)

  1. 暂无评论