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); }; })()