سؤال

I'm writing a Chrome extension for Stack Overflow, and need to rerun a check when the page updates (i.e. comments/answers are added to the content).

I've tried subscribing to $(document).ajaxComplete(), but that never seems to fire.

I've found that binding to DOMSubtreeModified allows me to update correctly, but it appears to be firing too often. On a page load, it can be called 21 times (Sometimes it is only called once though). Equally, if I perform a jquery selection in the console, the event fires again multiple times.

$(setup);

var hits = 0;
var original_title;

function setup()
{
    original_title = document.title;
    doWork();
}

function doWork()
{
    //unbind so our own changes don't cause infinite loops of the event.
    $("#mainbar").unbind("DOMSubtreeModified", findSkeets);

    //Debug: Add the Number of function hits to the title bar
    hits++;
    document.title = "(" + hits + ") " + original_title;

    //Do Work Here
    
    //Rebind to the event now that we've finished executing;
    $("#mainbar").bind("DOMSubtreeModified", findSkeets);
}

Is there a more efficient method of monitoring for changes to the page? I've seen a couple of Chrome hangs on Stack Overflow, that might be a result of this extension, so I'd like to minimise the impact as much as possible.

هل كانت مفيدة؟

المحلول

DOMSubtreeModified is part of the obsolete Mutation Events API, which has been deprecated (among other reasons) for being notoriously inefficient. According to MDN, DOM Mutation Eventsis a feature that "has been removed from the Web", "is in the process of being dropped" and "Web apps using it may break at any time".

You should use the new MutationObserver API, which is also more efficient.
(The mutation-summary library now provides a useful inteface to this new API.)

See, also, this answer for more details and this answer for a similar usecase: A Chrome Extension using the MutationObserver API to detect (and decorate) asynchronously loaded Google search results.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top