Last active
August 29, 2015 14:22
-
-
Save flangofas/6419083e5b86dd2806fc to your computer and use it in GitHub Desktop.
Image Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Image loader | |
*/ | |
var ImageLoader = function() { | |
//Constructor | |
}; | |
/** | |
* This function can be used to load heavy images(when page is loaded) | |
* or dynamic images which we don't want to load with their container at once. | |
* As soon as the image is loaded, it can then be added to a HTML Element | |
* i.e. document.body.appendChild(preLoadImg('//lorempixel.com/400/200/')). | |
* Also, it is stored in browser's cache and can be used whenever is needed | |
* without making an new HTTP request. i.e. <img src="//lorempixel.com/400/200/" />. | |
* However, it is not | |
* | |
* @param string|object string should be filepath. Object is merged | |
* with Image object so you have all its properties. | |
* @return object empty|object empty object for unsupported param types or | |
* Image object. | |
*/ | |
ImageLoader.prototype.preload = function(given) { | |
var i = {}; | |
if (typeof given === 'string') { | |
i = new Image(); | |
i.src = given; | |
} else if (typeof given === 'object' && | |
Array.isArray(given) === false) { | |
i = new Image(); | |
i = this.mergeObjs(i, given); | |
} | |
return i; | |
} | |
/** | |
* Handy function for merging objects and keeping | |
* the first object to its current state. i.e. Image Object. | |
* | |
* @param object f first object | |
* @param object s second object | |
* @return object extended first object | |
*/ | |
ImageLoader.prototype.mergeObjs = function(f, s) { | |
for (var prop in s) { | |
if (s.hasOwnProperty(prop)) { | |
f[prop] = s[prop]; | |
} | |
} | |
return f; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment