开发者

Javascript executing when jQuery not ready

The following scenario is a problem I am having. I came to the conclusion that jQuery must not be ready when Javascript is executing by observing this scenario.

Scenario:

I have a Java application which injects Javascript script tags into the currently loaded DOM page. The following Java code runs inline Javascript which inserts jquery.js and myCode.js. myCode.js holds my Javascript codes.

 browser.executeJavaScript("var head= document.getElementsByTagName('head')[0];" +
                                "var script= document.createElement('script');script.type= 'text/javascript';script.src= 'jquery.js';head.appendChild(script);" +
                                "var script4= document.createElement('script');script4.type= 'text/javascript';script4.src= 'http://myCode.js';head.appendChild(script4);");

In this Java application, I also have a buttonListener that fires a function in myCode.js in ActionPerformed();

executedJS = browser.executeJavaScript("replaceAllLinks()");

The problem that is encoun开发者_如何学Gotered is nullPointerException at the above line when button is clicked. Accomodating for null case results in endless loop without any changes.

while(executedJS == null) browser.executeJavaScript("replaceAllLinks()");

The cause of the problem was pinpointed down to when jQuery functions, methods are present inside replaceAllLinks(); javascript function. when jQuery, methods were absent, no problems could be observed. There was not one instance of nullPointerException raised.

The only possible underlying issue would be that somehow jQuery library is not fully loaded while replaceAllLinks(); is being executed. If jQuery methods and functions were not in use, it doesn't matter and everything runs okay.

My question is then, how can I make sure that jQuery is fully loaded and available for use?


Every script relying on jQuery should be contained inside a DOM ready function. Such a function normally takes this form:

$(document).ready(function() {
    /* code here */
});

and a shortcut to achieve the same thing would be:

$(function() {
    /* code here */
});

Here's the documentation for further information on the ready method: http://api.jquery.com/ready/


Declare some global variable at the end jquery.js, e.g.

window.jQueryIsLoaded=true;

and check this variable before using jQuery.

<edit>Forget this, see Salman A's comment below, should be the right answer.</edit>

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜