How can I be notified when an element is added to the page?

前端 未结 8 2142
别跟我提以往
别跟我提以往 2020-11-22 16:11

I want a function of my choosing to run when a DOM element is added to the page. This is in the context of a browser extension, so the webpage runs independently of me and I

8条回答
  •  耶瑟儿~
    2020-11-22 16:50

    Between the deprecation of mutation events and the emergence of MutationObserver, an efficent way to be notified when a specific element was added to the DOM was to exploit CSS3 animation events.

    To quote the blog post:

    Setup a CSS keyframe sequence that targets (via your choice of CSS selector) whatever DOM elements you want to receive a DOM node insertion event for. I used a relatively benign and little used css property, clip I used outline-color in an attempt to avoid messing with intended page styles – the code once targeted the clip property, but it is no longer animatable in IE as of version 11. That said, any property that can be animated will work, choose whichever one you like.

    Next I added a document-wide animationstart listener that I use as a delegate to process the node insertions. The animation event has a property called animationName on it that tells you which keyframe sequence kicked off the animation. Just make sure the animationName property is the same as the keyframe sequence name you added for node insertions and you’re good to go.

提交回复
热议问题