在Chrome扩展中使用Jquery如何保证执行顺序?

例如,网页会有如下代码:

$(document).ready(function() {
  web()
});

我希望在确保web()已经执行的情况下再执行我的自定义函数,该如何实现?望大神赐教,谢谢

阅读 5.4k
4 个回答

你是想问怎么在页面原生的脚本执行完再执行植入的 content script 吧?

Chrome 的 Content Script 有一个 run_at 属性可以配置

https://developer.chrome.com/extensions/content_scripts

run_at

Optional. Controls when the files in js are injected. Can be
"document_start", "document_end", or "document_idle". Defaults to
"document_idle".

In the case of "document_start", the files are injected after any
files from css, but before any other DOM is constructed or any other
script is run.

In the case of "document_end", the files are injected immediately
after the DOM is complete, but before subresources like images and
frames have loaded.

**In the case of "document_idle", the browser chooses a time to inject
scripts between "document_end" and immediately after the window.onload
event fires. The exact moment of injection depends on how complex the
document is and how long it is taking to load, and is optimized for
page load speed. **

Note: With "document_idle", content scripts may not necessarily
receive the window.onload event, because they may run after it has
already fired. In most cases, listening for the onload event is
unnecessary for content scripts running at "document_idle" because
they are guaranteed to run after the DOM is complete. If your script
definitely needs to run after window.onload, you can check if onload
has already fired by using the document.readyState property.

即使是 document_idle,应该也没有办法精确捕获到原生的脚本是否已经执行完了,所以有一个可行的方法就是手动进行检测,
脚本抛入后就运行一个检测方法,第隔一段时间执行一次(比如:100ms),检查是否已经定义了某个全局变量,或者某个期望的节点是否存在,如果满足标志条件,结事定时器,执行你的植入代码的逻辑。

可以参考一个 SO 上的这个回答

window.addEventListener ("load", myMain, false);

function myMain (evt) {
    var jsInitChecktimer = setInterval (checkForJS_Finish, 111);

    function checkForJS_Finish () {
        if (    typeof SOME_GLOBAL_VAR != "undefined"
            ||  document.querySelector ("SOME_INDICATOR_NODE_css_SELECTOR")
        ) {
            clearInterval (jsInitChecktimer);
            // DO YOUR STUFF HERE.
        }
    }
}

在web函数里面执行你的函数就可以了吧,或者你这个在web()写回调,然后在回调里写你的自定义函数。

把你的自定义函数作为参数传给web,web函数执行完相关代码后再执行回调函数

web(cb) {
    //code here
    if(typeof cb === 'function') {
        cb();
    }
}

$.when可以看看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题