1. Technology

Media Specific JavaScript

By

CSS has supported media queries for some time. All browsers in current use will recognise simple media queries such as 'screen' or 'handheld'. More modern browsers even allow for more complex media tests such as testing the width of the viewport.

JavaScript has supported updating the content of the web page, including the CSS, for some time as well.

By combining these two together we can easily add media query support to JavaScript where our scripts are only loaded when the particular media query is satisfied.

There are three parts to the scripting that you need to do this.

The first part you need is a function that can dynamically add JavaScript into a web page. We'll call this to add different JavaScript code to our web page depending on the particular media that the browser supports.

The second piece of code we need is a JavaScript function to test whether the web page supports the specific media. Now I usually write my own versions of all the JavaScript I present here but the solution that Nicholas Zakas wrote for testing the media type is simple and straightforward for performing this function so I can't see any point in not using it, particularly since he has made it available for others to use.

The key to the whole thing is the third part of the JavaScript which we need to custom write to meet the specific requirements of the page. It basically consists of an if statement calling the isMedia functiom to test if the media we want is supported and then calling the addJavaScript function to load the JavaScript needed for that media.

For example if we want to load screen800.js when the media query "screen and (max-width:800px)" is supported by the browser then all we need to call to do this is to use the following with the first two functions:


if (isMedia("screen and (max-width:800px)")
addJavascript('screen800.js','body');

Simply repeat that code substituting the desired queries and the names of the scripts to include to dynamically include whatever scripts you want with whatever media queries you want.

  1. About.com
  2. Technology
  3. JavaScript
  4. Script Library
  5. Function Library
  6. Media Specific JavaScript

©2014 About.com. All rights reserved.