等待脚本对象加载 [英] Waiting for a script object to load

查看:90
本文介绍了等待脚本对象加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个jQuery脚本,该脚本将从google chrome的控制台运行并分析页面. 我的问题是,当我运行以下代码时:

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:

第1步:

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

第二步:

alert($('a'));

效果很好,我得到了[object],这是我想要的结果.

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?

推荐答案

通常,您需要在script nodes onload 事件上附加一个侦听器. jQuery在完全传输并执行之前将不可用.喜欢

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);

上面的代码相当坚固,并且也可以在IE6 +中使用.

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

这篇关于等待脚本对象加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆