Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Chrome Extension content script, must I wait for document.ready before processing the document?

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.

like image 795
David Mills Avatar asked Feb 25 '11 03:02

David Mills


People also ask

Where does document ready function go?

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.

Where do you put the document ready in HTML?

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.


1 Answers

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"     }   ],   ... } 
like image 77
Mohamed Mansour Avatar answered Sep 18 '22 09:09

Mohamed Mansour