How to Detect DOM Manipulations (With jQuery)

| Comments

Detecting any changes in the current DOM is not an easy task even though some current browsers support to listen to mutation events. These mutation events got recently deprecated in favor of DOM Mutation Observers and for a good reason. Mutation events cause performance issues and lacking of cross browser support. The mutation events look promising but specification is still a draft and I guess that it would take a while until they are fully supported on all major browsers.

If you still need to detect changes like me and you are using jQuery (or any other library) to do your manipulation you can use this gist to hook into your library to detect changes. Instead of detecting changes on the DOM we just detect manipulating function calls. This plugin injects a function call after a jQuery function was called. The configuration is fairly easy. jQuery.hook(‘append’, myFunc) would call myFunc after jQuery.append was called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
 * Function hook jQuery plugin
 * version 1.0
 * author: Damien Antipa
 * http://github.com/dantipa/
 */
(function(window, $, undefined){

    /**
     * Hooks into a given method
     * 
     * @param method
     * @param fn
     */
    $.fn.hook = function (method, fn) {
        var def = $.fn[method];

        if (def) {
            $.fn[method] = function() {
                var r = def.apply(this, arguments); //original method
                fn(this, method, arguments); //injected method
                return r;
            }
        }
    }

})(window, jQuery);

Copyright © 2014 - Damien Antipa. Powered by Octopress