Skip to content
Advertisement

Javascript event that is triggered when browser loads new inline (ajax) content?

Is there a Javascript event that is triggered when browser loads new inline (ajax) content? I would like to catch new content as it happens inside my browser extension. Thanks to all

window.onload = function() {
    var observer = new MutationObserver(function(mutations) {
        alert("hello");
    });

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

    observer.observe($('#contentArea'), config);
}

Advertisement

Answer

Using the DOM Mutation Observer will most likely be what you want.

// Since you are using JQuery, use the document.ready event handler
// which fires as soon as the DOM is fully parsed, which is before
// the load event fires.
$(function() {
    var observer = new MutationObserver(function(mutations) {
        alert("DOM has been mutated!");
    });

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

    // You must pass a DOM node to observe, not a JQuery object
    // So here, I'm adding [0] to extract the first Node from 
    // the JQuery wrapped set of nodes.
    observer.observe($('#contentArea')[0], config);
    
    // Then, the DOM has to be mutated in some way:
    $("#contentArea").html("<p>test</p>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="contentArea"></div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement