MutationObserver 是浏览器提供的一个DOM API,用于监视 DOM 树的变动。然而IE11 不支持 MutationObserver,只支持旧的 DOMMutationObserver DOM API。
- // 检查浏览器是否支持 MutationObserver
- if ('MutationObserver' in window) {
- // 使用 MutationObserver
- var observer = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutation) {
-
- });
- });
- } else {
- // 不支持则使用 DOMMutationObserver
- var observer = new MutationObserver(function(mutations) {
- mutations.forEach(function(mutation) {
- if (mutation.type === 'childList') {
- var addedNodes = mutation.addedNodes;
- for (var i = 0; i < addedNodes.length; i++) {
- var node = addedNodes[i];
-
- }
- } else if (mutation.type === 'attributes') {
-
- }
- });
- });
- observer.observe(document.body, {
- childList: true,
- attributes: true,
- characterData: true,
- subtree: true,
- attributeOldValue: true,
- attributeFilter: ['class', 'id']
- });
- }
DOMMutationObserver DOM API只支持 childList 和 attributes 两种类型的变动。