Skip to main content

Javascript For Deferring Until jQuery Loaded

By May 22, 2017Blog, Javascript, jQuery
Allure Web Solutions Code Snippet

This snippet is for deferring running of any jQuery code until jQuery is loaded onto the page. This function is useful if you need to call your jQuery somewhere on your page, rather than in a specific JS file that you know is being loaded after jQuery. One downside of the method is that if jQuery for some reason is never loaded, the timeout function will continue to run indefinitely, which could have a negative impact on performance.

The Defer Function

(function defer(method) {
  if (window.jQuery) {
    method();
  } else {
    setTimeout(function () {
      defer(method)
    }, 50);
  }
})();

// Credits: http://stackoverflow.com/a/17914854/3602355

The defer function will call itself every 50ms until window.jQuery exists at which time it exits and call method()

Usage

defer(function () {
    // do something
});

// OR

function doSomething() {
    // do something
}
defer(doSomething());
allure

Author allure

More posts by allure

Leave a Reply

Designed by

best down free | web phu nu so | toc dep 2017