I am trying to find a way to store .jpg files from my website into the localstorage to increase the site speed. Theoretical its simple: convert the picture.jpg into a base64 string and store it with setitem into the localstorage. to display the picture again just load the base64 string from the localstorage and decode back to jpg. But, as always, the practice is more difficult. Im trying to find a way to convert the .jpg files on-the-fly to base64 using html5 or javascript (no php!). Does someone had the same problem and was able to find a solution and could share the code?
Only string values can be stored in local storage - this will not be a problem, and we'll see in this post how we'll store a collection of images along with some data for each.
On the downside, localStorage is potentially vulnerable to cross-site scripting (XSS) attacks. If an attacker can inject malicious JavaScript into a webpage, they can steal an access token in localStorage. Also, unlike cookies, localStorage doesn't provide secure attributes that you can set to block attacks.
localStorage can only store Strings, while modern Javascript can also handle binary files. For example, the result of a fetch can be retrieved as a Blob .
I'm also for using HTML5 cache manifest which supports the offline case too and is designed for your problem. Don't use local storage with base64 because:
For Cache Manifests you can look to w3.org - Cache Manifests also on html5 Rocks there is a beginner guide.
If you do not want to use HTML5 chache manifest, you should try to increase the speed as much as possible, described in many posts here on stackoverflow, i liked the link to the presentation in the post about increasing Math Object
You can use canvas
element and toDataURL
method where supported. Something like that:
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function() {
canvas.width = this.width;
cavans.height = this.height;
ctx.drawImage(this, 0, 0);
var base64jpeg = canvas.toDataURL("image/jpeg");
}
img.src = "/images/myjpeg.jpg";
But if you want to do that to "increase the site speed", use HTML5 manifest for caching: it was designed exactly for that purpose (and offline app, of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With