概要
Firefox, Chrome等においてMutationObserver
でattributeFilter
を使った場合には動作するが、EdgeではSyntax Error
が発生した際の覚書
コード
const ob = new MutationObserver((mutations, observer)=> {
console.log(mutations, observer)
})
ob.observe(document, {
childList: true,
subtree: true,
attributeFilter: ["height"],
})
子要素の追加や削除高さの変更を見ようとこのようなコードを書いたが、このコードはEdgeだと構文エラーになる
※attributeFilter: ["height"]
を指定しても検知される変更はElement.height
の値だけなのでスタイルの変更や内容の変化からの高さの変化自体は検知されません。
修正版
const ob = new MutationObserver((mutations, observer)=> {
console.log(mutations, observer)
})
ob.observe(document, {
attributes: true,
childList: true,
subtree: true,
attributeFilter: ["height"],
})
attributes: true
この一行を追加したら問題なくなる
原因
Stack OverFlowで下記の回答を見つけた。
With a MutationObserver, it's possible to filter attributes, but only if you are observing element attributes to begin with. Therefore the option attributeFilter is only applicable if attributes is set to true.
If you specify an attributeFilter without setting attributes to true, then IE11 will throw a syntax error, while Chrome and Firefox will just silently ignore attributeFilter.
To resolve the syntax error, either set attributes to true or remove the attributeFilter.
つまりattributeFilter
を使うにはattributes
を有効にしておく必要がある。
ChromeやFirefoxではattributes
を有効にせずにattributeFilter
を利用するとattributeFilter
の設定をエラー出さずに無視するが、IE11(Edgeでも)ではsyntax error
になるとの事。
確かにattributes
を有効にするとEdgeでエラーは出なくなるのだが、MDNでは
If this property is specified, there's no need to also set attributes to true, as it's implied
とのようにattributeFilter
を指定していればattributes
をtrue
にする必要は無いとの記述を見つけたので試してみた。
検証
ブラウザ | attributeFilterとattributes | attributeFilterのみ |
---|---|---|
Edge | 問題なし | Syntax Error |
Chrome | 問題なし | 問題なし |
Firefox | 問題なし | 問題なし |
という結果になった。
あとがき
今回の検証ではChromium ベースでない古いEdgeを利用したので、新しい方ではChromeやFirefoxと同じ挙動になるかも。
とりあえず、attributeFilter
使う際はattributes
も設定しておくと良いかも。