JSのDOM監視のためのWebAPI「MutationObserver」について。基本的な使い方とサンプルコードに加え、PhotoSwipe(v5)とSwiper(v8)の連携デモを使った特殊なケースでの使い方について紹介しています。

seen from Malaysia

seen from Malaysia

seen from Malaysia

seen from Israel

seen from United Kingdom

seen from Netherlands
seen from United States
seen from Germany

seen from United Kingdom

seen from United Kingdom

seen from Malaysia
seen from Colombia
seen from Netherlands

seen from Spain

seen from United Kingdom

seen from Ireland

seen from Italy
seen from United Kingdom
seen from Netherlands

seen from Canada
JSのDOM監視のためのWebAPI「MutationObserver」について。基本的な使い方とサンプルコードに加え、PhotoSwipe(v5)とSwiper(v8)の連携デモを使った特殊なケースでの使い方について紹介しています。

Anya is live and ready to show you everything. Watch her strip, dance, and perform exclusive shows just for you. Interact in real-time and make your fantasies come true.
Free to watch • No registration required • HD streaming
Userscript 內對於 SPA 類的頁面的修改
Userscript 內對於 SPA 類的頁面的修改
目前的 userscript 支援這四種啟動時機 (用 @run-at 參數指定):
document-start (一開始就跑)
document-body (出現 body 後跑)
document-end (DOMContentLoaded 時,或是之後跑)
document-idle (DOMContentLoaded 後跑)
但對於 SPA 類的頁面來說,即使用到 document-idle,也不保證執行時頁面已經渲染完成,這時候可能是 framework 才正要開始處理頁面的時候。
如果我們的 userscript 想要「等」這些 framework 處理完後再開始跑,其中一種 workaround 是用 setTimeout() 等,但這樣很容易被 side effect 影響,像是電腦慢一點的時候還是會失敗,而如果 setTimeout() 時間拉太長體驗又不好:
set…
View On WordPress
Tumblrで動的に追加された記事に対してhighlight.jsで強調表示する
Tumblrでhighlight.jsを使ってソースコードを強調表示しているブログというのは多々あると思う。 ここのブログもそのうちのひとつだけど。
最初にページを表示したときに存在する要素に対しては強調表示できるのだけど、 下までスクロールしていったときに動的に追加される要素に対しては普通にhighlight.jsを使っているのでは当然ながら強調表示されない。
せっかくスクロールしていくと記事が動的に追加されるのに、 ソースコードの箇所が強調表示もされず見辛いのは悲しいので、 どうにかならないかと思い、MutationObserverを使って要素が追加されるのを監視して、追加されたらhighlight.jsを再度実行するというコードを書いた。
コードは以下の通り。jQueryとhighlight.jsが使用できる必要がある。
$(function(){ 'use strict'; var codeAreaSelector, postAreaSelector, MutationObserver, observer; function highlight(selector) { return $(selector).each(function(index, element) { hljs.highlightBlock(element); }); } codeAreaSelector = '.body-text code:not(.hljs)'; postAreaSelector = '#posts'; highlight(codeAreaSelector); MutationObserver = window.MutationObserver || window.WebkitMutationObserver || window.MozMutationObserver; if (!MutationObserver) { return; } observer = new MutationObserver(function(mutations) { highlight(codeAreaSelector); }); observer.observe($(postAreaSelector).get(0), { childList: true, subtree: true }); });
既に強調表示の処理が行われた要素に対して再度実行しないように (実行しても問題ないのかもしれないが) jQueryに渡すセレクタ内で:not(.hljs)を指定して要素を除外している。
あとは記事が追加される親要素に対してMutationObserverで監視をして、 追加されたらhljs.highlightBlockで強調表示するようにしている。
今のところ想定通り動作してくれている。
もう少し言えばMutationEventsに対応すればより良いのだろうけど、Tumblrを見ているユーザがInternet Explorerの古いものを使っていたりとか、それ以外のブラウザでも妙に古いバージョンのものを使っているとは思えない(思いたくない)ので対応しなかった。