javascript - 在Chrome扩展中使用Jquery如何保证执行顺序?
天蓬老师
天蓬老师 2017-04-11 10:29:15
[JavaScript讨论组]

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

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

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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(4)
ringa_lee

你是想问怎么在页面原生的脚本执行完再执行植入的 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();
    }
}
PHP中文网

$.when可以看看

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号