1

When loading JavaScript libraries (like jQuery), they tend to create an object on the Window element.

I'm trying to work out how I can detect when the library has just loaded so I've gone down the path of trying to detect a property change on the window object...

window.addEventListener("DOMAttrModified", invalidate, false);

function invalidate(evt)
{
    console.log('attrChange = ' + evt.attrChange);
}

... This doesn't work.

Perhaps someone knows of another way to solve both this solution and a mechanism to detect when an external library has loaded.

p.s. I have looked at the onload tag for the script tag but I'm concerned as it's not in the W3C.

p.p.s. Ultimately, I'm trying to implement a function where it is safe to use jQuery code.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nick Middleweek
  • 1,049
  • 2
  • 11
  • 19

1 Answers1

0

If your js code is lower then script tag then don't worry, html rendering stops while script tag is not loaded, so if your js is lower then library is already loaded.

Also you may check for existence of some variable (like $).

if (typeof jQuery != 'undefined') {
  // is loaded
} else {
  // is not loaded
}

Or in loop though interval:

var interval = setInterval(function () {
  if (typeof jQuery != 'undefined') {
    clearInterval(interval);
    // do what you want
  }
});
Danil Speransky
  • 29,891
  • 5
  • 68
  • 79
  • Hey, thanks for your reply... 1). I'm not a fan of using timed loop checks, I think Events are the correct way to go here... 2). I've tried to find documentation around loading external JavaScript through a SCRIPT SRC and then having code in another SCRIPT tag below that references the external JS code but I can't find anything that states the browser will wait until it's fully loaded before continuing... Is it just a known 'thing'? I can't believe there's not an Event based solution to this, perhaps like the INITIALISE Event in Flash/ Flex? Thanks for your help! – Nick Middleweek Jul 31 '12 at 23:03
  • I'm working on a project that has jquery wrapped up in a require bundled .js file but I need to make a UI style change before the require bundle has loaded. My thinking is that as soon as jQuery is initialised I can execute `$('document').ready(function(){ //UI style change code here });` – Nick Middleweek Aug 01 '12 at 13:22
  • I'm hoping that I can have a listener on the window object, that executes each time a property is added to it. Then in that listener I check if it was "jQuery" that was added, and then I execute the .ready() function, etc... – Nick Middleweek Aug 01 '12 at 13:25