Last active
January 12, 2023 09:57
-
-
Save ppbntl19/c9bd6c44cbb56d3732937a6ffaef0dcc to your computer and use it in GitHub Desktop.
This is a java script code that allow image caching offline for a graphic element
This file contains 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
//This is a javascript code that allow image caching offline for a graphic element | |
//This example is using html 5 File Api to get image data. | |
//Please replace current component id with your graphic element id | |
localstorage_image_cache("722c-e69a-c6db"); | |
//Save image in local storage | |
function localstorage_image_cache(graphic_image_component_id) { | |
//Return if browser is not firefox | |
if (typeof InstallTrigger == 'undefined') return; | |
// LocalStorage with image | |
var storage_files = JSON.parse(localStorage.getItem(graphic_image_component_id)) || {}, | |
//Get Image | |
graphic_image = document.querySelector("#component-" + graphic_image_component_id + " img"); | |
//Display error if component not found | |
if (!graphic_image) return alert("Please use a valid component id .e.g. 722c-e69a-c6db "); | |
//Set Image src again to make sure emit onload event | |
graphic_image.src = graphic_image.src; | |
//Execute logic | |
$(graphic_image) | |
.one('load', function() { | |
if (graphic_image.complete && graphic_image.naturalHeight !== 0) { | |
console.log("image loaded successfully") | |
var xhr = new XMLHttpRequest(); | |
xhr.onload = function() { | |
var reader = new FileReader(); | |
reader.onloadend = function() { | |
// Save image as a data URL | |
storage_files.graphic_image = reader.result; | |
// Set name for localStorage | |
storage_files.src = graphic_image.src; | |
// Save as JSON in localStorage | |
try { | |
localStorage.setItem(graphic_image_component_id, JSON.stringify(storage_files)); | |
} | |
catch (e) { | |
console.log("Storage failed: " + e); | |
} | |
} | |
reader.readAsDataURL(xhr.response); | |
}; | |
xhr.open('GET', graphic_image.src); | |
xhr.responseType = 'blob'; | |
xhr.send(); | |
} | |
else { | |
//Get iamge from local storage | |
$(graphic_image).attr({ | |
'src': storage_files.graphic_image | |
}); | |
} | |
}) | |
.on('error', function() { | |
// Use image from localStorage | |
$(graphic_image).attr({ | |
'src': storage_files.graphic_image | |
}); | |
}); | |
} | |
//End |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment