开发者

How to execute a function when jQuery is loaded?

开发者 https://www.devze.com 2023-03-28 08:37 出处:网络
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'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开发者_C百科 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?


Just for the records, completeness 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 compatibility, 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 == 'complete' ) )
    {
      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 recommend that one

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


Michael is right. You could also use this shorthand

$(function() {
    // Code for on docload here
});
0

精彩评论

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