Skip to content

Instantly share code, notes, and snippets.

@stevenschobert
Created July 13, 2016 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenschobert/c3b762201786481c9c7a68679a5527ab to your computer and use it in GitHub Desktop.
Save stevenschobert/c3b762201786481c9c7a68679a5527ab to your computer and use it in GitHub Desktop.
Demonstrating how programmatically loading images in HTML pages affects network calls
<html>
<body>
<title>Image Preloading Test</title>
<meta charset="utf-8" />
</body>
<div id="target">Loading...</div>
<button id="load">start</button>
<script>
var url = "https://unsplash.it/800/800";
document.getElementById("load").addEventListener("click", function() {
var img = document.createElement("img");
img.src = url;
img.onload = function() {
var el = document.getElementById("target");
el.innerHTML = "LOADED!";
setTimeout(function() {
// no network call, because its the document node in memory
el.appendChild(img);
// network call based on cache policy of first load, because its a new
// node in memory. if content is the same, load is faster though
el.innerHTML = "<img src=\"" + url + "\" />";
// network call similar to above, because its a new node in memory
el.innerHTML = "<div style=\"background-image: url(" + url + "); width: 800px; height: 800px;\">background</div>";
}, 1000);
};
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment