Coder Social home page Coder Social logo

mutationobserver.js's Introduction

MutationObserver

Browser Test Status
Note: the svg swapped the working browsers; IE8 works while IE7 fails 1 test

A polyfill for the MutationObserver API (can I use?). The polyfill is more cause we can than should (with subtree at any rate)... It's async and uses a recursive timeout fallback (default checks changes every 30ms + runtime) instead of using the deprecated DOM3 MutationEvents so theoretically can support virtually any environment.

$ npm install mutationobserver-shim
$ bower install MutationObserver-shim

CDN

<script src="//cdn.jsdelivr.net/npm/mutationobserver-shim/dist/mutationobserver.min.js"></script>

Polyfill differences from standard interface

MutationObserver

  • Implemented using a recursive setTimeout (every ~30 ms) rather than using a setImmediate polyfill; so calls will be made less frequently and likely with more data than the standard MutationObserver. In addition, it can miss changes that occur and then are lost in the interval window.
  • Setting an observed elements html using innerHTML will call childList observer listeners with several mutations with only 1 addedNode or removed node per mutation. With the standard you would have 1 call with multiple nodes in addedNodes and removedNodes node lists.
  • With childList and subtree changes in node order (eg first element gets swapped with last) should fire a addedNode and removedNode mutation but the correct node may not always be identified.

MutationRecord

  • addedNodes and removedNodes are arrays instead of NodeLists
  • oldValue is always called with attribute changes
  • nextSibling and previousSibling correctfullness is questionable (hard to know if the order of appended items). I'd suggest not relying on them anyway (my tests are extremely permissive with these attributes)

Supported MutationObserverInit properties

Currently supports the following MutationObserverInit properties:

  • childList: Set to truthy if mutations to target's immediate children are to be observed.
  • subtree: Set to truthy to do deep scans on a target's children.
  • attributes: Set to truthy if mutations to target's children are to be observed. As explained in #4, the style attribute may not be matched in ie<8.
  • attributeFilter: Set to an array of attribute local names (without namespace) if not all attribute mutations need to be observed.
  • attributeOldValue: doesn't do anything attributes are always called with old value
  • characterData: currently follows Mozilla's implementation in that it will only watch textNodes values and not, like in webkit, where setting .innerHTML will add a characterData mutation.

Performance

By default, the polyfill will check observed nodes about 25 times per second (30 ms interval) for mutations. Try running these jsperf.com tests and the JSLitmus tests in the test suite for usage performance tests. It may be worthwile to adapt MutationObserver._period based on UA or heuristics (todo).

From my tests observing any size element without subtree enabled is relatively cheap. Although I've optimized the subtree check to the best of my abilities it can be costly on large trees. You can draw your own conclusions based on the JSLitmus and jsperf tests noting that you can expect the mo to do its check 28+ times a second (by default).

Although supported, I'd recommend against watching attributes on the subtree on large structures, as the check is complex and expensive on terrible hardware like my phone :(

The included minified file has been tuned for performance.

Compatibility

I've tested and verified compatibility in the following browsers + these Sauce browsers

  • Internet Explorer 8 (emulated), 9, 10 in win7 and win8
  • Firefox 4, 21, 24, 26 in OSX, win7 and win8
  • Opera 11.8, 12.16 in win7
  • "Internet" on Android HTC One V
  • Blackberry 6.0.16

Try running the test suite and see some simple example usage:

See http://dev.opera.com/articles/view/mutation-observers-tutorial/ for some sample usage.

mutationobserver.js's People

Contributors

megawac avatar mnaoumov avatar arfaian avatar delros avatar gheoan avatar gyeates avatar kilian avatar meirionhughes avatar rafeca avatar siawo avatar

Stargazers

Monir Abu Hilal avatar Ian Maurmann avatar jacker avatar  avatar James Carragher avatar Radosław Włodkowski avatar Roman avatar Robiul H. avatar  avatar  avatar Saurin Dashadia avatar  avatar Leo S. avatar  avatar  avatar  avatar dreamapple avatar LGD.HuaFEEng avatar 天马行空 avatar lhuanyu avatar Jhonne Jefferson avatar Dmitry avatar  avatar  avatar  avatar myxvisual avatar Front_end_er avatar  avatar 罗圈圈 avatar  avatar  avatar great avatar Kotaro Sugawara avatar SENTHILKUMAR S avatar Beier (Bill) avatar Yuhei Yasuda avatar PungsKi001 avatar 志平 刘 avatar Martin zhang avatar jzwb avatar Delgado avatar sclchic avatar Johnatan Dias avatar Tim Huang avatar Erwin avatar  avatar 39 avatar honsa.ch avatar 翁润雨 avatar 成雨 avatar Alexandra Hegyi avatar Cleam Lee avatar Frank avatar icode avatar  avatar jofunLiang avatar cen avatar  avatar Leif Olsen avatar Paul Bishop avatar Dan avatar Danil avatar Chafic Najjar avatar Lou Yunlong avatar Clement Fradet Normand avatar  avatar xueyushuai avatar Andy avatar Ming avatar  avatar dirge avatar Francis Luz avatar Cat  avatar dragon avatar ice breaker avatar kamesh sethupathi avatar alwayrun avatar Brett Jankord avatar Pete Richardson avatar anganToio avatar Tom Meiselbach avatar Hyeungshik Jung avatar Laughing avatar  avatar saasfreelancer avatar 随心 avatar  avatar Benji avatar zhangolve avatar Viktor Hubert avatar svrakata avatar 刘炬光 avatar Aidan avatar 唐焱鑫 avatar Sean Dove avatar Austin Biggs avatar bqxu avatar Steve Hanna avatar  avatar Marco Otte-Witte avatar

Watchers

Tobias Buschor avatar Alex Zaytsev avatar Itay Adler avatar Maurizio F avatar Andrey avatar James Cloos avatar Frank.Liu avatar  avatar karall avatar South Drifted avatar

mutationobserver.js's Issues

Added and remove nodes through off mutation record count

var div = document.createElement("div");
var a = document.createElement("a");
var b = document.createElement("b");
var c = document.createElement("i");
div.appendChild(a);
observer.observe(div, {
     childList: true
});
div.insertBefore(b, a);
div.insertBefore(c, a);

Calls with 3 mutations (thinks a moves position) instead of 2

Not working with SSR

Hi, it's not working with SSR because window is undefined. Please add a window && !window.MutationObserver check. Thanks!

Add support for Browserify

This line does not work in browserify, because this is not the window:

this.MutationObserver = this.MutationObserver || this.WebKitMutationObserver || (function(){/* ... */})(void 0);

Changing it to this works:

this.MutationObserver = window.MutationObserver || window.WebKitMutationObserver || (function(){/* ... */})(void 0);

ie7 Style Attributes don't register

Quirksmode calls .attributes compat "A bloody mess." We use indexed attributes (relevant section)... Here's some highlights of problems to address

  • Do yourself a favour and don't use the indexed attributes array.
  • IE7 and lower don't return the value of a style attribute.
  • IE 5.5 doesn't return custom attributes, and initially gives the attribute value instead of an attribute object.
  • IE7 and lower give null for style values.
  • IE 5.5 initially gives the value of the attribute; not the attribute object.
//Issue
var attributeTest = document.createElement("i");
attributeTest.style.width = "140px";
attributeTest.attributes.style.value ~~ "width: 140px;" //normally (browser dependent case, semi etc)
//ie<7
attributeTest.attributes.style.value === "null" //shit...

bower.json malformed

Bower reports two errors with this package's bower.json:

bower invalid-meta  The "name" is recommended to be lowercase, can contain digits, dots, dashes
bower invalid-meta  The "main" field cannot contain minified files

Because of this, some commands like bower list won't work in projects where this package is installed.

Crashed in IE9 and IE8

I faced such issue in IE9 and IE8 during the integration of MutationObserver.JS to one of our projects. The MutationOserver object initialized with such preferences:

app.util.observeDOMModification($cache.loginPopup, {
    'attributes' : true,
    'attributeFilter' : [ 'height', 'style' ],
    'childList' : true,
    'subtree' : true
}, loginPopupModifiedHandler);

Please, take a look on screenshot, so you can see the actual error message and the place where it has been thrown.

image

Seems like the issue appears due not correct input parameter to the "reduce" function.

Could you please suggest the possible work around for such case?

Observing attributes or charData on subtree misses new elements

var observer = new MutationObserver($.noop);
observer.observe(document, {
    attributes: true,
    subtree: true
});
var $crossDocEl = $("body", document).append("<div id='test'>").find("#test");
observer.takeRecords();
$crossDocEl.attr("foo", "boo");
var records = observer.takeRecords();

// records === []

As new element test isn't observed!

TypeError: Cannot read property 'length' of undefined when observe(document, ...)

When I invoke

myObserver.observe(document, { attributes: true, characterData: true, childList: true, subtree: true });

I got the following errors

TypeError: Cannot read property 'length' of undefined
    at reduce (/Users/Ricky/Documents/gaia/node_modules/mutationobserver-shim/MutationObserver.js:537:40)
    at copy (/Users/Ricky/Documents/gaia/node_modules/mutationobserver-shim/MutationObserver.js:462:38)
    at clone (/Users/Ricky/Documents/gaia/node_modules/mutationobserver-shim/MutationObserver.js:479:11)
    at createMutationSearcher (/Users/Ricky/Documents/gaia/node_modules/mutationobserver-shim/MutationObserver.js:173:25)
    at Object.MutationObserver.MutationObserver.WebKitMutationObserver.MutationObserver.observe (/Users/Ricky/Documents/gaia/node_modules/mutationobserver-shim/MutationObserver.js:105:21)

I think problem arise from [1]. $target.attributes means document.attributes, but we don't have any document.attributes and throw error. We should give a empty object if someone try to observe document.

[1] https://github.com/megawac/MutationObserver.js/blob/master/MutationObserver.js#L462

Failed to parse source map from '/xxx/dist/MutationObserver.js'

hey, I received a warning in the terminal console,as follows

warning  in ./node_modules/mutationobserver-shim/dist/mutationobserver.min.js

Module Warning (from ./node_modules/source-map-loader/index.js):
Failed to parse source map from '/Users/xxx/node_modules/mutationobserver-shim/dist/MutationObserver.js' file: Error: ENOENT: no such file or directory, open '/Users/xxx/node_modules/mutationobserver-shim/dist/MutationObserver.js'

Can you help me? I haven't found the answer anywhere else

Release 0.2.6?

There have been a number of commits and improvments since 0.2.5, including better modularization and fixes to #5 and #6. What work is involved in tagging a new release? This shim is a great help when testing with phantom-js, and I'd love to see a new release instead of just having to keep up to date with master.

characterData mutation not detected

Ref systemjs/systemjs/issues/1157. This shim silently breaks SystemJS as the characterData mutation used in its Promise polyfill is not detected:

        var scheduled;
        var node = document.createTextNode('');
        var o = new MutationObserverShim(run);
        o.observe(node, { characterData: true });

                // run is never called
        function run() {
            var f = scheduled;
            scheduled = void 0;
            f();
        }

        var i = 0;
        return function (f) {
            scheduled = f;
            node.data = (i ^= 1);
        };

The documentation seems to suggest that characterData mutations are handled, but looking at the code path I'm not sure how. Is the code above meant to work with the shim? Thanks!

IE8 examples are not working

Hi,
I was looking for pollyfils like yours in IE8 to use it as DOMNodeInserted event, but when I started checking example in ie8 under windows 7 , I have discovered that those samples don't work at all, for instance image is loaded with errors.

Change license

Hey there, this module is being used as a subdependency of a module my project relies on. Unfortunately I'm working on a project that has strict license requirements, and requires me to only use modules that have one of the more common licenses (MIT, Apache 2.0, BSD-2/3 etc.)

Would you be open to changing the license on this project to something like MIT, that maintains the same spirit as the WTFPL, but is a little bit more broadly recognized? Thanks!

Support for subtree

Hi,

thanks a lot for the shim, it's very helpful.

Is there any way to get support for observing the subtree of a node? Observing childList only reports changes to immediate children of a node, but anything that happens further down remains undetected.

Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.