Imageコントロールを作成してみました。きっかけは画像の遅延読み込みを実現したいことと、ロード中はローディング中を示す画像を表示したかったからです。
いつの間にかimgタグのlowsrcは廃止になっているんですね
- DOWNLOAD(jQueryとDQ coreライブラリが必要です)
- DEMO
解説
基本は、(new Image()).srcにimageのURIを指定するだけですが、ロード中画像を表示するためにターゲットとなる画像の読み込みが終わるまで非表示にしておいて、onloadイベントでimgタグを切り替えています。
if (options.preview) {
// ターゲットとなるimgタグは非表示にして、プレビュー画像を表示しておく
this.client.hide();
this._preview = $('<img />')
.attr('src', options.preview)
.appendTo(this.obj);
}
this.client.attr('src', options.src || "");
options.alt && this.client.attr('alt', options.alt);
this.client.bind('load', this, function (e) {
// 画像が読み込み終わったらプレビュー画像を非表示にしてい
// 代わりにターゲットの画像を表示する
var me = e.data;
me._preview && me._preview.hide().remove();
me.client.show();
options.onLoad && options.onLoad.apply(me, arguments);
});
this.client.bind('error', this, function (e) {
// 画像の読み込みに失敗しても同じ
var me = e.data;
me._preview && me._preview.hide();
me.client.show();
options.onError && options.onError.apply(me, arguments);
});
使い方
new DQ.Image(親コントロール, オプション)
オプション
| 名前 | 説明 |
|---|---|
| src | 表示したい画像のURIを指定 |
| preview | 画像読み込み中の代替画像を指定 |
| alt | 設定したいimgタグのalt属性値を指定 |
使用例
<header>
<link href="css/dq-core.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<!-- ライブラリの読み込み //-->
<script src="../js/dq.js" type="text/javascript"></script>
<script src="js/dq-image.js" type="text/javascript"></script>
</header>
<body>
<!-- Imageコントロールの外観を定義 //-->
<div id="image1" style="width: 400px; height: 300px;">
</div>
<script type="text/javascript">
DQ.afterLoad(function () { <!-- ライブラリの読み込み完了を待つおまじない //-->
<!-- Imageコンロトールの作成 //-->
new DQ.Image(DQ.page(), {
src: "images/image.jpg",
preview: "images/loading.gif"
}, 'image1');
</script>
</body>