Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function when jQuery is loaded?

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?

like image 952
js-coder Avatar asked Feb 03 '26 09:02

js-coder


2 Answers

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();
like image 102
ManoCarayannis Avatar answered Feb 06 '26 01:02

ManoCarayannis


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);
like image 35
pimvdb Avatar answered Feb 06 '26 00:02

pimvdb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!