JS Image 加载

var imgLoad = function (url, callback) {
    var img = new Image();
    img.src = url;
    if (img.complete) {
        callback(img.width, img.height);
    } else {
        img.onload = function () {
            callback(img.width, img.height);
            img.onload = null;
        };
    };
};

 改进版:

var imgLoad = function (img, url, callback) {
    if (!img)
        img = new Image();
    img.src = url;
    if (img.complete) {
        isFunction(callback) && callback(img.width, img.height);
    } else {
        img.onload = function () {
            isFunction(callback) && callback(img.width, img.height);
            img.onload = null;
        };
    };
};
var isFunction = (function () { // Performance optimization: Lazy Function Definition 
    return "object" === typeof document.getElementById ? isFunction = function (fn) { try { return /^\s*\bfunction\b/.test("" + fn); } catch (x) { return false } } : isFunction = function (fn) { return "[object Function]" === Object.prototype.toString.call(fn); };
})()

 

posted @ 2014-07-11 16:23  allvie  阅读(713)  评论(0编辑  收藏  举报