36

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.

David Mills
  • 2,326
  • 1
  • 22
  • 25

2 Answers2

69

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"
    }
  ],
  ...
}
fregante
  • 23,010
  • 11
  • 97
  • 127
Mohamed Mansour
  • 36,569
  • 9
  • 110
  • 87
  • 4
    Agree if you want to check Document is loaded the above mention approach is good. But the DOM updates can happen even after Document is loaded. This could be AJAX functionality. Like add a listener for "DOMSubtreeModified". window.addEventListener("DOMSubtreeModified", (event) -> console.log "DOMSubtreeModified", event ) – Feru Mar 08 '16 at 15:59
3

Short answer: yes.

Long answer: jQuery won't be able to grab any DOM elements that aren't already rendered. I know i've gotten into trouble a few times and it can be quite annoying to debug something for awhile and then realize I forgot to wrap the code in a document.ready. If its working for you, it's because your lucky. Also, you dont need to wrap it in a document.ready if your scripts are at the bottom of your page, just above your closing body tag.

thinkdevcode
  • 911
  • 1
  • 8
  • 13
  • 2
    That's a good point about scripts at the bottom of the page. Where/when are Chrome extension content scripts evaluated? – David Mills Feb 25 '11 at 03:51
  • According to the Chrome Timeline (Developer Tools), the extensions are loaded last. So you very well may not have to use document.ready – thinkdevcode Feb 25 '11 at 03:54
  • Short answer: **Only if you use `document_start`.** Both `document_idle` (the default) and `document_end` run after dom ready. – fregante Jan 04 '17 at 17:45