みかづきブログ その3

本ブログは更新を終了しました。通算140万ユーザーの方に観覧頂くことができました。長い間、ありがとうございました。

👆

引越し先はこちらです!

JavaScriptで背景画像の読み込み終了を検知する

前回つくったpreloadの仕組み だと、JavaScriptがpreloadする画像のパスを知っている必要がありました。(preloadするパスのリストを渡す必要があったため)


JavaScriptで画像の読み込み終了を検知する - みかづきブログ その3


しかしこれだと、例えばcompassで生成したスプライト画像など、CSSしかファイル名を知らなくても良い画像のpreloadがうまくいきません。
そこで、preloadの仕組みをパスのリストを渡す方式ではなく、preloadクラスのついたDOMのbackground-imageにするように仕様を変更してみました。


JavaScript

(function(win, doc, ns) {

    "use strict";

    function watch(selector, callback) {
        var preload = doc.querySelectorAll(selector),
            i = preload.length,
            list = [],
            count = 0,
            max = 0,
            imgList = [],
            url, img,
            MS = 500;

        while(i) {
            --i;
            url = (preload[i].style["background-image"] || win.getComputedStyle(preload[i], "")["background-image"]);
            url = url.replace(/^url\(/, "").replace(/\)$/, "");
            
            if (/^http/.test(url)) {
                ++max;
                img = new Image;
                doc.body.appendChild(img);
                img.width = img.height = 1;
                img.onload = _count;
                img.src = url;
                imgList.push(img);
                img = null;
            }
        }

        function _count() {
            setTimeout(function() {
                var _this = this,
                    i = length;
    
                if (++count === length) {
                    while (i) {
                        doc.body.removeChild(imgList[--i]);
                   }
                    callback();
                }
            }, 0);
        }  
    }

    ns.LoadManager = {
        watch: watch
    };

})(this, document, App);

つかいかた

(function(win, doc, ns) {

    "use strict";
    
    // preloadを行いたいDOMのセレクタとコールバックを渡す
    ns.LoadManager.watch(".preload", function() {
        doc.getElementById("wrapper").style.opacity = 1;
        console.log("LOAD_END.");
    });

})(this, document, App);

DEMO



querySelector とか getComputedStyle とかをつかっているのでIE9からしか動きません。
今回は以上です。