mic angelo
mic angelo

Reputation: 115

Chrome extension: must delay page load until javascript finishes

My extension reformats an ugly page that I visit often. Currently, the page first loads un-fixed, then there is a ~100ms delay, then my JS formats the html.

How do I prevent the uncorrected html from ever displaying?

My JS file is defined in the manifest as follows:

,"content_scripts": [{
        "matches": ["*://*.<url goes here>.com/*"],
        "js": ["js/1.js"]
}]

Upvotes: 0

Views: 1654

Answers (2)

Ga&#235;l Barbin
Ga&#235;l Barbin

Reputation: 3929

You can set run_at: "document_start" in your manifest. Add a rule to hide the page, and differ your current script in a window.onload event.

If you are visiting often this page, you could even load first your template/redesign, and then integrate the page data that you want from a cache or from the source.

Upvotes: 2

Xan
Xan

Reputation: 77571

You need to adjust the run_at parameter.

By default, content scripts are executed after the page is fully loaded (at "document_idle").

Try adding "document_end" first and see if it improves the delay.

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.

"content_scripts": [{
  "matches": ["*://*.example.com/*"],
  "js": ["js/1.js"],
  "run_at": "document_end"
}]

This may still be too late. There's a final option, "document_start", that you can use, but beware - it executes really early, before any of the DOM is ready. There's nothing yet for you to correct.

You can wait for an element to appear and correct it immediately though, for instance.

You may also try to correct things with CSS injection. This can be safely inserted at "document_start" with no extra tricks.

P.S. Or, for example, use Gael's answer - add a CSS rule to hide the body, wait until the page is loaded (for instance, with DOMContentLoaded event), correcting it and then removing/overriding the CSS rule.

Upvotes: 3

Related Questions