Specifically, I'm evaluating all of the images on a page to see if they have a certain attribute, and then adding some new <divs> to the DOM based on those attributes. Must I wait for document.ready to fire before performing these modifications in order to be guaranteed that Chrome has loaded all of the necessary pieces of the DOM?
The problem I'm running into is that sometimes document.ready takes a short while to fire and the user is already browsing around the page, wondering why my extension hasn't yet had any effect. The problem usually only lasts a moment, but it's enough to be annoying.
If I don't bother waiting for document.ready, and instead immediately process the document, everything seems to work; but I wonder if I'm just getting lucky.
The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded.
The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser). You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed.
Actually, you don't have to wait. You can process right away in Content Scripts. Just make sure you don't use document_start
in the run_at
attribute.
In document_end
, the files are injected immediately after the DOM is complete, but before subresources like images and frames have loaded. document_idle
(the default value) happens even later.
{ "name": "My extension", ... "content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mystyles.css"], "js": ["jquery.js", "myscript.js"], "run_at": "document_end" } ], ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With