Conditionally load Javascript based on media query | Responsive Web Design

Best practice for a long time has been to load your javascript at the end of the document to improve website performance, however in todays world of mobile devices we need an even faster solution.

Responsive design has provided us with the ability to change the way the content is displayed to the end user. Most of the time we follow best practices and reorder the content into a linear page layout allowing the most relevant content to float to the top.

Sometimes, however, we fall back on display: none; for content that might not be appropriate to load onto a particular breakpoint.

There are plenty of bad examples of this, but a good example might be to hide an advanced mapping application on the mobile in favour of linking the user to a built in phone feature. Although we display:none the element the javascript that drives that feature is still downloaded in a responsive design world.

In this case you could look at the width of the device and determine if it is of a certain size you could load in the resources,

if (screen.width >= 600) {
	// download complicated script
	// swap in full-source images for low-source ones
}

or alternatively you could look at the width of the viewport which is more favourable.

@media all and (max-width: 900px) {
	// styles
}

if (document.documentElement.clientWidth < 900) {
	// scripts
}

This is only the start of what is possible.  Check out some of the articles below that take this even further

Subscribe to our Newsletter

Add your email address and receive an email every Friday covering off everything worth knowing about building your websites responsively.