This uses HTML5 data attributes to load the image according to the screen width. For example, for laptops. it loads only laptop-sized images. saving bandwidth and optimizing speed.
//---------------------------Setting ViewPort Widths-----------------------//
var sSize=768; // High End Mobile Phones
var mSize=1024; // Tables like Ipad Or Something..
var lSize=1336; // Laptop 15 Inch
var xlSize=1500; // Desktop 22 Inch And Above
//------------------------------ Grabbing Images in Images Array ------------//
var images = document.getElementsByTagName('img');
//--------------------------------Checking Current Resolution Function -----------///
function checkRes()
{
var width = document.documentElement.clientWidth; // grab the width of the screen //
var currentFlag=""; // To Check the Final Resolution
// --------------------- Paths of Img To Grab ---------------------------//
var xlImgPath='data-xl';
var lImgPath='data-l';
var mlmgPath='data-m';
var slmgPath='data-s';
//------------------------------ Set CurrentFlag to the Current Browser Size /////////
if (width>=xlSize) {
currentFlag="xl";
}
else if (width>=lSize )
{
currentFlag="l";
}
else if (width>=mSize )
{
currentFlag="m";
}
else if (width<=sSize )
{
currentFlag="s";
}
//------------------------------- Cycle through all the Images And Attach the Proper Src ---------//////////
for (var i = 0; i < images.length; i++)
{
var thisImage=images[i]; // Grab Current Image //
var defaultImgSource =images[i].getAttribute('src'); // grabs the Current image src (The Default Image)
//-------------------------------------- Switch Case Accoring to Current Size ------------------
switch(currentFlag){
case 'xl':
if (thisImage.getAttribute(xlImgPath)!==null) // If Desktop Image has been defined..
{
thisImage.src=thisImage.getAttribute(xlImgPath); // Set The path of Image to Desktop Path
}
else
{
thisImage.src=defaultImgSource; // Else Set the Fefaut src image
}
break;
case 'l':
if (thisImage.getAttribute(lImgPath)!==null)
{
thisImage.src= thisImage.getAttribute(lImgPath);
}
else
{
thisImage.src=defaultImgSource;
}
break;
case 'm':
if (thisImage.getAttribute(mlmgPath)!==null)
{
thisImage.src=thisImage.getAttribute(mlmgPath);
}
else
{
thisImage.src=defaultImgSource;
}
break;
case 's':
if (thisImage.getAttribute(slmgPath)!==null)
{
thisImage.src=thisImage.getAttribute(slmgPath);
}
else
{
thisImage.src=defaultImgSource;
}
break;
}
}
};
//---------------------------------Run The Function On Page Load ---------------------
checkRes();
HTML
<img
src="http://s30.postimg.org/rjm6iy2kh/default.jpg"
data-s="http://s4.postimg.org/4gmjg2m7h/image.jpg"
data-m="http://s4.postimg.org/4gmjg2m7h/image.jpg"
data-l="http://s4.postimg.org/4gmjg2m7h/image.jpg"
data-xl="http://s4.postimg.org/4gmjg2m7h/image.jpg" >