サーバーから読み込まれる前に、いくつかの読み込みアニメーションを画像にバインドするプラグインを作成しようとしています。一部のケースを除いて、正常に動作します。DOM 構造の変更を意味します。私のプラグインのロジックは次のとおりです。
(function( window ){
'use strict';
var $ = window.jQuery;
var console = window.console;
var hasConsole = typeof console !== 'undefined';
var methods = {
// plugin initialization
init : function( options ) {
return this.each(function(){
methods._applyImagepreloader.apply( this, options);
});
},
// working with each object
_applyImagepreloader: function() {
// if has class imagepreloader, do nothing
if ($(this).hasClass('imagepreloader'))
return;
// if the image has determined size
var width = $(this).width();
var height = $(this).height();
$(this)
.clone()
.attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
.attr('width', width)
.attr('height', height)
.addClass('imagepreloader')
.insertAfter(this);
$(this).hide();
$(this).load(function(){
$(this).next('.imagepreloader').remove();
$(this).fadeIn();
});
}
};
$.fn.imagepreloader = function( options ) {
return methods.init.apply( this, options );
};
})( window );
現在、ページが AJAX によって更新され、新しいイメージ タグが表示されると、プラグインが機能しません。調査を行ったところ、DOM ミューテーション イベントが役立つことがわかりましたが、理解したとおり、それらはすべてのブラウザーでサポートされているわけではありません。さらに、setinterval を使用して DOM 構造の変更をキャッチすることもできますが、それはベスト プラクティスではないと思います。そのため、JQuery のオン/ライブ イベントで問題が解決されている可能性があります。彼らがどのように機能するのだろうか。新しい DOM 要素の出現をどのようにキャッチできますか?