{"id":181,"date":"2016-09-14T18:59:27","date_gmt":"2016-09-14T18:59:27","guid":{"rendered":"http:\/\/mead.design\/?p=181"},"modified":"2016-09-14T21:33:21","modified_gmt":"2016-09-14T21:33:21","slug":"build-a-lazy-image-loader-in-js","status":"publish","type":"post","link":"https:\/\/meaddesign.net\/portfolio\/build-a-lazy-image-loader-in-js\/","title":{"rendered":"Build a Lazy Image Loader in JS"},"content":{"rendered":"<p>I have recently been having a lot of fun teaching an interaction design class, and had been wanting to play around with building a lazy image loader that displays a blurry low resolution very small image initially, then fades in a high resolution, larger, sharp image asynchronously, after that image has loaded.<!--more--> You can see a good implementation of this type of effect on <a href=\"http:\/\/medium.com\">medium.com<\/a>.<\/p>\n<p>My strategy is to simply have a small blurry image load, then once the full sized image has loaded add it to the DOM and just put it right on top of the small image. The fade in effect can be achieved with just a little CSS. Take a look at this <a href=\"https:\/\/meaddesign.net\/demo\/lazyload\/example1.html\">simple demo<\/a> to see it in action. Let&#8217;s take a look at the code. You can see in the HTML markup, only the small image is in the file&#8230;<\/p>\n<pre class=\"font:sourcecodepro toolbar:2 lang:xhtml decode:true\">&lt;body&gt;\r\n\r\n&lt;header id=\"loader\"&gt;\r\n\t&lt;img src=\"smallphotos\/photo1.jpg\" alt=\"museum\"&gt;\r\n&lt;\/header&gt;<\/pre>\n<p>Then, after the body tag I added this simple JavaScript&#8230;<\/p>\n<pre class=\"toolbar:2 lang:js decode:true\">&lt;script&gt;\r\n\tvar image = new Image();\r\n\timage.src = \"largephotos\/photo1.jpg\";\r\n\t\r\n\timage.onload = function () {\r\n\t\t\r\n\t\tconsole.log(\"Image loaded!\");\r\n\t\t\r\n\t\tvar theImage = document.createElement('img');\r\n\t\ttheImage.src = \"largephotos\/photo1.jpg\";\r\n\t\ttheImage.className = \"fullsized fade\";\r\n\t\tdocument.getElementById('loader').appendChild(theImage);\r\n\t}\r\n\t\r\n&lt;\/script&gt;\r\n<\/pre>\n<p>Line 2 creates a new image object and line 3 assigns the source. At this point, the browser will start downloading the source file from the server. The anonymous function on line 5 runs once the image has completely downloaded \u2013 however long that takes. This function then creates a new image element, assigns the source file to it (the one we just downloaded and is now in the cache). It then assigns two classes to the image and adds it to the header, which has an ID of loader.<\/p>\n<p>Let&#8217;s take a quick look at the two classes that were added.<\/p>\n<pre class=\"toolbar:2 lang:css decode:true \">.fullsized {\r\n\tposition: absolute;\r\n\ttop:0;\r\n\tleft: 0;\r\n\twidth: 100%;\r\n}\r\n\r\n.fade {\r\n\tanimation: fadein 2s ease-out forwards;\r\n}\r\n\r\n@keyframes fadein {\r\n\tfrom {\r\n\t\topacity:0;\r\n\t}\r\n\tto {\r\n\t\topacity:1;\r\n\t}\r\n}<\/pre>\n<p>You can see that the fullsized class is absolutely positioning the image on top of the low resolution blurry image. The fade class fades it in, giving an effect of going from blurry to clear. Note that I have left all the browser prefixes off the fade and keyframes rules for simplicity.<\/p>\n<p>It is interesting to point out, that in this case, the images are actually elements on the page. This technique works just as well if you want to load the images as background images in the CSS. Check out the <a href=\"https:\/\/meaddesign.net\/demo\/lazyload\/example2.html\">second demo<\/a> to see a version that loads the images as background elements in CSS.<\/p>\n<pre class=\"toolbar:2 lang:js decode:true \">&lt;script&gt;\r\n\t\r\n\tvar image = new Image();\r\n\r\n\timage.src = \"largephotos\/photo1.jpg\";\r\n\r\n\timage.onload = function() {\r\n\r\n\t\tconsole.log(\"Image loaded!\");\r\n\r\n\t\tvar theContainer = document.createElement('div');\r\n\t\ttheContainer.className=\"loader fade\";\r\n\t\tdocument.getElementById('lazyload').appendChild(theContainer);\r\n\r\n\t}\r\n\t\r\n&lt;\/script&gt;<\/pre>\n<p>The difference here is that instead of having the anonymous function add an image element to the page, it adding a div. The loader class that is attached to the DIV uses the high resolution image in the background.<\/p>\n<pre class=\"toolbar:2 lang:css decode:true \">.loader {\r\n\tposition: absolute;\r\n\ttop:0;\r\n\tleft: 0;\r\n\twidth: 100%;\r\n\theight: 0;\r\n\tpadding-top:27.1739%;\r\n\tbackground-image: url(largephotos\/photo1.jpg);\r\n\tbackground-size: cover;\r\n}<\/pre>\n<p>Ok, that is great, but what if you want to load more than one image on the page this way? Take a look at <a href=\"https:\/\/meaddesign.net\/demo\/lazyload\/example3.html\">example 3<\/a>. Here is the modified script at the bottom of the page&#8230;<\/p>\n<pre class=\"toolbar:2 lang:js decode:true \">&lt;script&gt;\r\n\t\r\n\tvar BgImages = ['photo1.jpg', 'photo2.jpg', 'photo3.jpg'];\r\n\r\n\tfor( var i=0; i&lt;BgImages.length; i++){\r\n\r\n\t\tvar image = new Image();\r\n\r\n\t\timage.src = 'largephotos\/'+BgImages[i];\t\r\n\r\n\t\timageLoad(i);\r\n\r\n\t}\r\n\r\n\tfunction imageLoad(incrementer){\r\n\r\n\t\timage.onload = function () {\r\n\t\t\tvar theContainer = document.createElement('div');\r\n\t\t\ttheContainer.style.backgroundImage = \"url(largephotos\/\"+BgImages[incrementer]+\")\";\r\n\t\t\ttheContainer.className=\"loader fade\";\r\n\t\t\tdocument.getElementsByClassName('lazyload')[incrementer].appendChild(theContainer);\r\n\r\n\t\t}\r\n\t}\r\n\t\r\n&lt;\/script&gt;<\/pre>\n<p>I manually built an array of images. This could be done programmatically, but for simplicity sake, I just made the array. Then the script loops through the array and creates a new image for each element in the array. At this point, the browser will start downloading all three images. Now the anonymous function has a name. This is necessary because of the way scope works in JavaScript. The incrementer is passed in so that each image can be added to the correct element.<\/p>\n<p>Ok, that is cool, but what if you want to make it so that the images don&#8217;t start downloading until they are visible on the page. Why make users download images they will not see, if they decide not to scroll down? Also, no point in having a cool fade in effect if no one can see it. Take a look at the <a href=\"https:\/\/meaddesign.net\/demo\/lazyload\/example4.html\">fourth and final example file<\/a>.<\/p>\n<p>The JavaScript here is a bit more complex, so we will build it in pieces&#8230;<\/p>\n<pre class=\"toolbar:2 lang:default decode:true\">window.addEventListener('scroll', function(){\r\n\r\n\tvar pageTop = document.body.scrollTop || document.documentElement.scrollTop\r\n\r\n\tconsole.log(pageTop);\r\n\r\n});<\/pre>\n<p>This event listener in the script at the bottom of the page will keep track of scrolling. The code on line 3 requires some explaining. ScrollTop is tracked differently in Chrome and Firefox (at least at this time). Chrome needs body.scrollTop, Firefox needs documentElement.scrollTop. Now it is pretty unusual to see an assignment statement like this, with the || or in it. Here is how it works: Depending on if you are in Chrome (webkit based browser) or Firefox (Mozilla based browser) one of those two statements will always be zero. JavaScript, when assigning a value to pageTop, will assign the one that has a value, since the other is essentially false. Weird, I know, but it works. Check it out in the console log.<\/p>\n<pre class=\"toolbar:2 lang:default decode:true \">var articles = document.getElementsByTagName('article');\r\nvar counter = 0;\r\n\r\n\r\nwindow.addEventListener('scroll', function(){\r\n\r\n\tvar pageTop = document.body.scrollTop || document.documentElement.scrollTop;\r\n\r\n\tif ( pageTop &gt; articles[counter+1].offsetTop ) {\r\n\r\n\t\tcounter++;\r\n\t}\r\n\r\n\tconsole.log(counter);\r\n\r\n});<\/pre>\n<p><span style=\"font-weight: 400;\">Add these two variables at the top of the script, then, in the script add an if statement that checks the position of offsetTop as we scroll for each article. The counter only gets incremented once we get past the top of the article. <\/span><span style=\"font-weight: 400;\">When we get to the bottom of the page, the counter increments to 3, which is beyond our article array, and so we start getting an error.\u00a0<\/span><span style=\"font-weight: 400;\">Notice, when you run this in the Chrome console, the counter gets checked hundreds of times for each article. That poses a challenge.<\/span><\/p>\n<p>Let&#8217;s deal with the error we get with the counter when we scroll past the top of the third article first.<\/p>\n<pre class=\"toolbar:2 lang:default decode:true \">var articles = document.getElementsByTagName('article');\r\nvar counter = 0;\r\nvar numOfArticles = articles.length;\r\n\r\n\r\nwindow.addEventListener('scroll', function(){\r\n\r\n\tvar pageTop = document.body.scrollTop || document.documentElement.scrollTop;\r\n\r\n\tif(counter &lt; numOfArticles-1){\r\n\r\n\t\tif ( pageTop &gt; articles[counter+1].offsetTop ) {\r\n\r\n\t\t\tcounter++;\r\n\t\t}\r\n\t}\r\n\r\n\tconsole.log(counter);\r\n\r\n});<\/pre>\n<p>Adding a variable to keep track of how many articles we have, and putting an IF statement in that only increments the counter if the counter is one less than the number of articles will do the trick. No more errors at the end of the page.<\/p>\n<p><span style=\"font-weight: 400;\">Now here is the tricky problem. I want to trigger loading each image once, based on the position of the scroll. <\/span><\/p>\n<p><span style=\"font-weight: 400;\">If I could set my loader to run when a certain pixel is hit during scrolling, that would work great. However, scrolling is somewhat unpredictable and I can be certain I will hit that specific pixel, especially if I am scrolling fast.\u00a0<\/span><span style=\"font-weight: 400;\">If I set it for a range of pixels, then the loader will run multiple times while I am scrolling in that range, and I only want it to fire ONE time for each image as it scrolls onto the page.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">Here is the solution I came up with&#8230;<\/span><\/p>\n<pre class=\"toolbar:2 lang:default decode:true \">var loaded = [];\r\n\r\nfor(var i=0; i&lt;numOfArticles; i++){\r\n\tloaded.push(0);\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">At the top of the script, with the other variables, make a new one called loaded and make it an empty array. Then I used a for loop to push a zero into the array for each article on the page.<\/span><\/p>\n<pre class=\"toolbar:2 lang:default decode:true \">window.addEventListener('scroll', function(){\r\n\r\n\tvar pageTop = document.body.scrollTop || document.documentElement.scrollTop;\r\n\r\n\tif(counter &lt; numOfArticles-1){\r\n\r\n\t\tif ( pageTop &gt; articles[counter+1].offsetTop ) {\r\n\r\n\t\t\tcounter++;\r\n\r\n\t\t\tif(loaded[counter] == 0){\r\n\t\t\t\tloaded[counter]++;\r\n\r\n\t\t\t\tconsole.log(\"array change fired\");\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\/\/console.log(counter);\r\n\r\n});<\/pre>\n<p>Then add one more IF statement to the event listener that will check to see if the value in the array is set to zero. If it is, increment it to 1. This way, the array will only be changed ONCE for each article, which is exactly what we need for our script. This is the hardest part. The rest is pretty much what we implemented in example 3.<\/p>\n<pre class=\"toolbar:2 lang:default decode:true \">var articles = document.getElementsByTagName('article');\r\nvar counter = 0;\r\nvar numOfArticles = articles.length;\r\nvar loaded = [];\r\n\/\/ add the array for the images again...\r\nvar BgImages = ['photo1.jpg', 'photo2.jpg', 'photo3.jpg'];\r\n\r\nfor(var i=0; i&lt;numOfArticles; i++){\r\n\tloaded.push(0);\r\n}\r\n\r\n\r\nwindow.addEventListener('scroll', function(){\r\n\r\n\tvar pageTop = document.body.scrollTop || document.documentElement.scrollTop;\r\n\r\n\tif(counter &lt; numOfArticles-1){\r\n\r\n\t\tif ( pageTop &gt; articles[counter+1].offsetTop ) {\r\n\r\n\t\t\tcounter++;\r\n\r\n\t\t\tif(loaded[counter] == 0){\r\n\t\t\t\tloaded[counter]++;\r\n\r\n\t\t\t\t\/\/console.log(\"array change fired\");\r\n\r\n\t\t\t\t\/\/ load the image for each article once when the image\r\n\t\t\t\t\/\/ gets to the top of the page\r\n\t\t\t\tvar image = new Image();\r\n\t\t\t\timage.src = 'largephotos\/'+BgImages[counter];\r\n\t\t\t\timageLoad(counter, image);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\/\/console.log(counter);\r\n\r\n});\r\n\r\n\/\/ Add the imageLoad function back in...\r\nfunction imageLoad(incrementor, image){\r\n\r\n\timage.onload = function () {\r\n\t\tvar theContainer = document.createElement('div');\r\n\t\ttheContainer.style.backgroundImage = \"url(largephotos\/\"+BgImages[incrementor]+\")\";\r\n\t\ttheContainer.className=\"loader fade\";\r\n\t\tdocument.getElementsByClassName('lazyload')[incrementor].appendChild(theContainer);\r\n\t}\r\n\r\n}<\/pre>\n<p>On line 6 I added the array for the photos back in. On line 30 put in the bit that actually loads the image when it gets to the top of the page. And finally, the imageLoad function is added at the bottom of the script. It has one additional argument, so that\u00a0we can know which we want to load as the page scrolls.<\/p>\n<p>The script is working well, except that the first image never loads. That is because it is already on the page when it loads and the user never scrolls to get to it. Also, I want the other images to load as they come into view, not when they get to the top of the page. Below is the slightly modified code and the final script.<\/p>\n<pre class=\"toolbar:2 lang:default decode:true \">var articles = document.getElementsByTagName('article');\r\nvar counter = 0;\r\nvar numOfArticles = articles.length;\r\nvar loaded = [];\r\n\/\/ add the array for the images again...\r\nvar BgImages = ['photo1.jpg', 'photo2.jpg', 'photo3.jpg'];\r\n\r\n\/\/ the height of the window, minus 200 pixels...\r\nvar height = window.innerHeight - 200;\r\n\r\nfor(var i=0; i&lt;numOfArticles; i++){\r\n\tloaded.push(0);\r\n}\r\n\r\n\/\/ Load the first image...\r\nvar image = new Image();\r\nimage.src = 'largephotos\/'+BgImages[counter];\r\nimageLoad(counter, image);\r\n\r\n\/\/ Load other images as they scroll into view...\r\nwindow.addEventListener('scroll', function(){\r\n\r\n\tvar pageTop = document.body.scrollTop || document.documentElement.scrollTop;\r\n\r\n\tif(counter &lt; numOfArticles-1){\r\n\r\n\t\tif ( pageTop &gt; articles[counter+1].offsetTop - height ) {\r\n\r\n\t\t\tcounter++;\r\n\r\n\t\t\tif(loaded[counter] == 0){\r\n\t\t\t\tloaded[counter]++;\r\n\r\n\t\t\t\t\/\/console.log(\"array change fired\");\r\n\r\n\t\t\t\t\/\/ load the image for each article once when the image\r\n\t\t\t\t\/\/ gets to the top of the page\r\n\t\t\t\tvar image = new Image();\r\n\t\t\t\timage.src = 'largephotos\/'+BgImages[counter];\r\n\t\t\t\timageLoad(counter, image);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\/\/console.log(counter);\r\n\r\n});\r\n\r\n\/\/ Add the imageLoad function back in...\r\nfunction imageLoad(incrementor, image){\r\n\r\n\timage.onload = function () {\r\n\t\tvar theContainer = document.createElement('div');\r\n\t\ttheContainer.style.backgroundImage = \"url(largephotos\/\"+BgImages[incrementor]+\")\";\r\n\t\ttheContainer.className=\"loader fade\";\r\n\t\tdocument.getElementsByClassName('lazyload')[incrementor].appendChild(theContainer);\r\n\t}\r\n\r\n}<\/pre>\n<p>Line 9 gets the height of the user&#8217;s window and subtracts 200 pixels from it. This variable is then used on line 27 making it so that the image will fade in once it is 200 pixels up from the bottom of the user&#8217;s window.<\/p>\n<p>To get the first image to load, I just added the original loading script on lines 16, 17 &amp; 18. This is an exact copy of the code from lines 38, 39 &amp; 40, but it will only load that first image.<\/p>\n<p>That is it! You can <a href=\"https:\/\/meaddesign.net\/demo\/lazyload\/lazyload.zip\">download the files<\/a> and play around with them. There are lots of ways this script can be modified to suit your specific needs. Have fun with it!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I have recently been having a lot of fun teaching an interaction design class, and had been wanting to play around with building a lazy image loader that displays a blurry low resolution very small image initially, then fades in a high resolution, larger, sharp image asynchronously, after that image has loaded.<\/p>\n","protected":false},"author":1,"featured_media":197,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[3],"tags":[12],"class_list":["post-181","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-development","tag-javascript"],"acf":[],"_links":{"self":[{"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/posts\/181","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/comments?post=181"}],"version-history":[{"count":16,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/posts\/181\/revisions"}],"predecessor-version":[{"id":198,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/posts\/181\/revisions\/198"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/media\/197"}],"wp:attachment":[{"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/media?parent=181"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/categories?post=181"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meaddesign.net\/portfolio\/wp-json\/wp\/v2\/tags?post=181"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}