简体   繁体   English

本机页面javascript完成执行后,如何执行扩展代码?

[英]How to execute extension code after native page javascript finishes executing?

These days many webpages have custom Javascript to execute things on page load. 如今,许多网页都有自定义Javascript来执行页面加载时的操作。 They either modify page content or load external widgets. 他们要么修改页面内容,要么加载外部小部件。

My extension tries to read the DOM and insert some data in the pages. 我的扩展程序尝试读取DOM并在页面中插入一些数据。 However in some cases where the page has its own Javascript, my extension executes before the page Javascript. 但是在某些情况下页面具有自己的Javascript,我的扩展名将在页面Javascript之前执行。

Due to that the page Javascript may overwrite my insertions or insert data which my extension cannot read. 因此,页面Javascript可能会覆盖我的插入内容或插入我的扩展名无法读取的数据。 How can I wait to execute my extension until after the page Javascript functions have loaded/executed? 在页面Javascript函数加载/执行之后,如何等待执行扩展?

Maybe this will help, but it has some undesired side-effects: 也许这会有所帮助,但是它会产生一些不良的副作用:

$(function () {
    setTimeout(function () {
        alert("At last!");
    }, 1000); // 1000 millis after page loaded and most probably all onload handlers have been run
});

The main side-effect is that it will be executed after 1000 millis so for that amount of time the user will see the unprocessed page and then your script will manipulate it. 主要的副作用是它将在1000毫秒后执行,因此在这段时间内,用户将看到未处理的页面,然后脚本将对其进行处理。 Under circumstances this may get ugly and be a detriment to the users' experience. 在某些情况下,这可能很难看,并且会损害用户的体验。


EDIT: 编辑:

You may also try this. 您也可以尝试一下。 On the body's end (inside, but at last) add this script tag: 在主体的一端(内部,但最后)添加以下脚本标记:

<script>
    $(function () { alert("LAST!"); });
</script>

By the rules of script execution and the fact that jQuery honors the order in which onload handlers are added through the $(function () { ... }); 通过脚本执行的规则以及jQuery遵循通过$(function () { ... });添加onload处理程序的顺序这一事实$(function () { ... }); idiom you can be pretty sure that your code is executed last. 成语,您可以确定代码最后执行。 The problem is that any asynchronous execution, such as AJAX callback handlers, will be executed out-of-order (that is, asynchronously in respect to the window.onload handlers that form a chain of responsibility ). 问题在于,任何异步执行(例如AJAX回调处理程序)都将无序执行(即,相对于形成责任链window.onload处理程序而言是异步的)。 To cope with that you need a pattern but it's probably overshoot. 为了解决这个问题,您需要一个模式,但这可能是过冲的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM