Reputation: 1814
I'm trying to cache my favicon image just like any other image, but I'm not seeing it in the cache, nor getting my confirmation console.log, nor seeing it when I disconnect from the internet (basically it is not caching).
I want to cache it so I can access it offline, so I can dynamically change the icon if the internet disconnects.
My html:
<link id="favicon" rel="icon" type="image/png" src="assets/favicon-red-16x16.ico.png">
My js:
// cache images
function preloadImages(array) {
if (!preloadImages.list) {
preloadImages.list = [];
}
var list = preloadImages.list;
for (var i = 0; i < array.length; i++) {
console.log('caching image...')
var img = new Image();
img.onload = function() {
console.log('image cached')
var index = list.indexOf(this);
if (index !== -1) {
// remove image from the array once it's loaded
// for memory consumption reasons
list.splice(index, 1);
}
}
list.src = array[i];
}
}
preloadImages(["../assets/favicon-green-16x16.ico.png", "../assets/favicon-red-16x16.ico.png"]);
question: Is it possible to cache the favicon client side? Is there another way to store it locally?
if i convert to base64 how do I store and grab it from local storage?
ps. using Chrome latest
<___ UPDATE ___>
Though the question is technically answered, How can I do this two store 2 (more than one) base64 image? I can't figure out how to draw 2 onto a canvas or 2 canvases.
Upvotes: 1
Views: 1318
Reputation: 1256
Try this code pal. You can hide iconImage img element. The other img tag i have used, is for testing only, so you can remove it.
<!DOCTYPE html>
<html>
<link id="favicon" rel="icon" href="img_the_scream.jpg" />
<body>
<img id="iconImage" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">
<br />
<img id="img" width="220" height="277"/>
<script>
function onLoadHandler() {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = document.getElementById("iconImage");
var base64Image = localStorage.getItem("lsFavicon");
var favicon = document.getElementById("favicon");
var img2 = document.getElementById("img");
if (base64Image == null && document.navigator.onLine) {
ctx.drawImage(img, 0, 0);
base64Image = canvas.toDataURL();
localStorage.setItem("lsFavicon", base64Image);
favicon.setAttribute("href", base64Image);
}
else if (base64Image != null) {
favicon.setAttribute("href", base64Image);
img2.setAttribute("src", base64Image);
}
}
window.onload = onLoadHandler;
</script>
</body>
</html>
Upvotes: 2