Search code examples
javascriptobservers

When loading the same script twice on a site, do observers stop observing from the first script?


I have this following piece of code in a rather complicated environment:

var cfg = { attributes: true, childList: true, characterData: true };

var observer = new MutationObserver(afunction);
observer.observe(e, cfg);

Before implementing a new idea of mine, I need to be assured if observer will automatically stop observing when I reload the same script meaning overwriting observer. Will it stop observing from the time it is overwritten or will it stop observing only when the garbage collector removes it?


Solution

  • It will only stop when the GC removes it. Javascript objects and variables don't retain any memory of the file whose code created them, so reloading the file doesn't have any effect on the objects that were created during a previous load.

    You could put an explicit check:

    var observer;
    if (observer) { // variable from a previous load of file
        observer.disconnect();
    }
    observer = new MutationObserver(afunction);