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

查看:199
本文介绍了javascript - 在Chrome扩展中使用Jquery如何保证执行顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

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

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

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

解决方案

你是想问怎么在页面原生的脚本执行完再执行植入的 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.
        }
    }
}

这篇关于javascript - 在Chrome扩展中使用Jquery如何保证执行顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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