0

These days many webpages have custom Javascript to execute things on page load. They either modify page content or load external widgets.

My extension tries to read the DOM and insert some data in the pages. However in some cases where the page has its own Javascript, my extension executes before the page Javascript.

Due to that the page Javascript may overwrite my insertions or insert data which my extension cannot read. How can I wait to execute my extension until after the page Javascript functions have loaded/executed?

1 Answers1

0

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. 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 () { ... }); 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). To cope with that you need a pattern but it's probably overshoot.

pid
  • 11,472
  • 6
  • 34
  • 63