Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset=utf-8 />
    <title>Responsive Images using Dynamic Base URL</title>
    
    <base href="http://placehold.it/1024/FF0000/">
    <script>
      function rebaseResponsiveImages(e){
        var assetURL = 'http://placehold.it/';
        
        // We can't use window.innerWidth from the start since it isn't available before rendering
        // and matchMedia isn't available in Firefox and other browsers.
        var windowWidth = window.innerWidth || screen.width;
        
        var widths = [
          160, 240, 480, 720, 960, 1024 // more than realistic for demo purposes
        ];
        
        // Find the largest size we can serve
        for(var i = widths.length-1; i >= 0; i--){
          if(windowWidth >= widths[i] || !i){
             assetURL += widths[i] + '/';
             break;
          }
        }
        
        assetURL += '00FF00/';
        var baseEl = document.getElementsByTagName('base')[0];
        if(baseEl.href == assetURL){
          // No change, so get outta here
          return;
        }
        
        // Update the <base href> for and touch each image so they get refreshed with the new base
        baseEl.href = assetURL;
        for(var i = 0, len = document.images.length; i < len; i++){
          document.images[i].setAttribute('src', document.images[i].getAttribute('src'));
        }
      };
      rebaseResponsiveImages();
      window.addEventListener('resize', rebaseResponsiveImages, false);
      document.addEventListener('DOMContentLoaded', rebaseResponsiveImages, false); // in case innerWidth is different than screen.width
    </script>
    <style>
      .pass { color:green; }
      .pass:after { content:" (pass)"; }
      .fail { color:red; }
      .fail:after { content:" (fail)"; }
    </style>
  </head>
  <body>
    <h1>Responsive Images using Dynamic Base URL</h1>
    <p>
      Proof of concept for <a href="http://blog.keithclark.co.uk/responsive-images-using-cookies/#comment-16">Schepp's comment</a>  
      on Keith Clark's <a href="http://blog.keithclark.co.uk/responsive-images-using-cookies/">Responsive images using cookies</a>. 
      No cookies needed!!! As a bonus, the image size will dynamically change when resizing the window.
    </p>
    <p>Image src: <span id=src>Loading…</span></p>
    <img src="FFF.png">
  </body>
</html>
 
window.onload  = function(e){
    var srcEl = document.getElementById('src');
    srcEl.textContent = document.images[0].src;
    srcEl.className += srcEl.textContent.indexOf('00FF00') != -1 ? 'pass' : 'fail';
};
Output 300px

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers