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

发布于 2022-09-02 16:03:11 字数 140 浏览 12 评论 0

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

橘寄 2022-09-09 16:03:11

你是想问怎么在页面原生的脚本执行完再执行植入的 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.
        }
    }
}
微暖i 2022-09-09 16:03:11

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

冷︶言冷语的世界 2022-09-09 16:03:11

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

web(cb) {
    //code here
    if(typeof cb === 'function') {
        cb();
    }
}
落花随流水 2022-09-09 16:03:11

$.when可以看看

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文