0

I'm using the following code snippet to detect changes in window.location.href inside of a Chrome extension for Hulu (among other streaming platforms) I need to execute myFunction once when Hulu is first opened and subsequently every time the URL changes as a result of clicking one of the links in the navbar.

(courtesy https://stackoverflow.com/a/46428962/6153940)

    var oldHref = document.location.href;

    window.addEventListener("load", function() {
        ########################################
        myFunction()
        ########################################

        var bodyList = document.querySelector("body"),
            observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (oldHref != document.location.href) {
                        oldHref = document.location.href;
                        ####################################
                        myFunction() once content has completely loaded
                        ####################################
                    }
                });
            });

        var config = {
            childList: true,
            subtree: true
        };

        observer.observe(bodyList, config);
    });

My problem: I only want to execute myFunction once the page has finished loading completely, so something like window.addEventListener("load", myFunction) except the load event isn't fired after a genre has been selected from the nav menu in Hulu, and neither is the DOMContentLoaded event. I'm not sure what the best way to achieve this is, or which event I should be listening for. Any thoughts appreciated, and feel free to ask for further clarification if necessary!

Sanchit Batra
  • 195
  • 1
  • 4
  • 17
  • 1
    Use [debounce](https://www.google.com/search?q=javascript+debounce) or simple setTimeout with `myFunction` for like 100ms or more. – wOxxOm Mar 09 '20 at 11:27
  • On a quick glance debounce seems better than the setTimeout I wanted to avoid, I'll give it a closer look and revert. Thanks for the input! – Sanchit Batra Mar 09 '20 at 11:32

0 Answers0