Vote count:
0
I am fairly new to JavaScript and have been trying to come up with a script of my own to dynamically serve smaller images to users on mobile devices.
Lets say I have a normal HTML image as follows:
<img id="test" src="http://ift.tt/1xjO0v1" />
I have then come up with a simple script that checks the page dimensions BEFORE any images are loaded (by using the DOMContentLoaded event). Depending on the incoming screen dimensions, it alters the image src to serve an image that is optimised to that screen size. This is the script:
document.addEventListener("DOMContentLoaded", function(event){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
if(x >= 1000)
{
var largeImage = true;
}
else if(x <= 999 && x >= 651)
{
var mediumImage = true;
}
else if(x <= 650)
{
var smallImage = true;
}
if(largeImage){
// Do nothing as the image is the right size (large)
}
if(mediumImage){
var imageSrc = document.getElementById("test").src.toString();
document.getElementById("test").src = imageSrc.replace("/myimage.jpg","/medium/myimage.jpg");
}
if(smallImage){
var imageSrc = document.getElementById("test").src.toString();
document.getElementById("test").src = imageSrc.replace("/myimage.jpg","/small/myimage.jpg");
}
});
Apologies for the horribly hacked up code, but it does actually work and saves a not inconsequential 2% on load times for mobile devices.
However, when I analyse the results using Google Page Speed Insights, I see that the page is still loading the original image (albeit somehow at a very small size, usually a few hundred bytes), as well as the new image as well. So my question is how is the original image being loaded, since my understanding of DOMContentLoaded is as follows:
"The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading" (taken from MDN)
And I know it's not really relevant to the question, but if anyone also has an SEO background, it would be useful to know if this kind of behaviour is damaging in any way from an SEO standpoint.
I would prefer to stick with JavaScript (as opposed to using JQuery), as a big part of this is about trying to learn the language and come up with something genuinely useful myself.
Thanks so much.
Using javascript to serve smaller images with DOMContentLoaded
Aucun commentaire:
Enregistrer un commentaire