Sebi
Sebi

Reputation: 4522

$(document).ready not firing

I have a content script from a chrome extension injected in a youtube page. Something like:

$(document).ready(function () {
  console.log("[INFO] Changes detected");
  myFunc();
}

When I refresh the script executes as expected. When I navigate in between pages, ready() does not fire. Does this mean that the document does not change? Inspecting the elements it obviously does.

Why isn't .ready() firing while navigating on a page?

Upvotes: 1

Views: 56

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370659

When navigating between /watch?v=VideoID videos on YouTube, you are essentially staying on the same page. Elements of the page get replaced with the help of XHR requests, but the document itself does not change.

You can see this if you open the Network tab and watch what happens when you navigate to a new video:

enter image description here

Notice how document is not any one of the request types there.

New documents are only loaded when you see document get requested, like in the following, where I press Enter from the address bar:

enter image description here

$(document).ready( only fires when a new page is loaded, not when parts of the current page get replaced with .innerHTML etc.

If you want to detect when parts of the page get replaced, use a MutationObserver.

Upvotes: 3

Related Questions