1

I'm trying to create a jquery script that will be run from the console of google chrome and will analyze a page. My problem is that when I run the following code:

var jq = document.createElement('script');
jq.src = "http://code.jquery.com/jquery-latest.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
alert($('a'));

I get a message box with null (bad result) But if I separate it to to executions like this:

step1:

var jq = document.createElement('script');
jq.src = "http://code.jquery.com/jquery-latest.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);

step2:

alert($('a'));

It works great and I get [object] that is my desired result.

The question is what can I do to run this in a single batch?

Niko
  • 26,516
  • 9
  • 93
  • 110
Noam
  • 4,472
  • 5
  • 30
  • 47

3 Answers3

2

In general, you need to attach a listener on the script nodes onload event. jQuery will not be available until its fully transfered and executed. Like

var jq   = document.createElement('script'),
    head = document.head || document.getElementsByTagName('head')[0] || document.documentElement;

    jq.src = "http://code.jquery.com/jquery-latest.min.js";
    jq.onload = jq.onreadystatechange = function() {
    if(!jq.readyState || /loaded|complete/.test( jq.readyState ) ) {
        jq.onload = jq.onreadystatechange = null;
        jq = undefined;
    }
}

head.insertBefore(jq, head.firstChild);

The above code is pretty much rocksolid and works in IE6+ aswell.

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

You could try something like this and check the ready state of the script:

jq.onreadystatechange = function() {
  if (this.readyState == 'complete') {
     alert($('a'));
  }
}
gherkins
  • 14,603
  • 6
  • 44
  • 70
0

If you want a solid way and tested listeners for a complete load of script, try third party libraries like: http://yepnopejs.com/

Start a script loader from scratch is not recommended, not Today.

Daniel Aranda
  • 6,426
  • 2
  • 21
  • 28