Created
July 10, 2013 18:38
-
-
Save powerc9000/5968915 to your computer and use it in GitHub Desktop.
Loads images and caches them in local storage. If the image exists in localStorage it loads it from the cache. NOTE: Because of cross origin policy it will only cache images belonging to the same domain as the webpage.
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
| //include your images like thus | |
| //<img data-src=""> | |
| (function(){ | |
| var cache = document.querySelectorAll("[data-src]"); | |
| var c = document.createElement("canvas"); | |
| var ctx = c.getContext("2d"); | |
| for(var i=0; i<cache.length; i++){ | |
| var el = cache[i]; | |
| var url = el.getAttribute("data-src"); | |
| var store = localStorage[url]; | |
| if(store){ | |
| el.src = store; | |
| } | |
| else{ | |
| (function(el, url){ | |
| var img = new Image(); | |
| var dataURI; | |
| img.src = url; | |
| img.onload = function(){ | |
| c.width = img.width; | |
| c.height = img.height; | |
| ctx.drawImage(img, 0,0, img.width, img.height); | |
| try{ | |
| dataURI = c.toDataURL("img/png"); | |
| localStorage[url] = dataURI; | |
| el.src = dataURI; | |
| } | |
| catch(e){ | |
| el.src = url; | |
| } | |
| } | |
| }(el, url)) | |
| } | |
| } | |
| }()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment