TOP
Home > Blog > Conditionally Load Resources Using jQuery

Conditionally Load Resources Using jQuery

Posted by Derek on April 7, 2015

Media queries are a wonderful thing. One of the most common uses is hiding things like large images and videos on small screen sizes. On a recent project I was using an embedded video as a background for a section of the home page. On small, narrow screens the user could see so little of it it did not make sense to show it (plus most mobile phone browser won't even render video). However, the video file is still requested and downloaded, slowing down the page.

I came across a great tutorial by Christian Heilmann on how to prevent this situation using matchmedia and a little JavaScript. However, I found that this pure JavaScript solution wasn't working in IE 10, at least in my situation. I converted it to use jQuery, which seems to be a bit more reliable. So, if you're loading jQuery on your site the example below is great way to prevent the loading of larger resources when they're not needed.

In this situation we're only loading a video on screen sizes larger that 660 pixels:

The HTML
<video id="bkgrd-vid" class="videobcg" autoplay preload="auto" loop="loop" muted="muted" volume="0" poster="/assets/images/vid-placeholder.jpg">
    <source class="mqdependent" data-media="screen and (min-width: 660px)" data-src="/assets/videos/vid-bkgrd.webm" type="video/webm" ></source>
    <source class="mqdependent" data-media="screen and (min-width: 660px)" data-src="/assets/videos/vid-bkgrd.mp4" type="video/mp4" ></source>
</video>
The JavaScript
$(function(){
  // Load media query dependent elements
  function mqLoad() {
    $('.mqdependent').each(function(){
      if ($(this).data('media') && window.matchMedia($(this).data('media')).matches) {
        $current = $(this);
        $.each($(this).data(), function(a,v) {
         if (a !== 'media') {
           $current.attr('src', v);
          }
        });
      }
    });
  }
  mqLoad();

  // For some browsers we need to explicitly load the video
  $('#bkgrd-vid')[0].load();

});

Leave a Reply



(Your email will not be publicly displayed.)


Captcha Code

Click the image to see another captcha.