How to load JavaScript conditionally with media queries in WordPress

I figured out a solution for loading JavaScript conditionally with media queries in WordPress, after a little research, and want to share it, and get some JavaScript criticism.

Scenario

I finished some scroll-driven animation with the help of the fantastically awesome Superscrollorama. I’m using min-width media queries to only render the animated elements in the browser above a certain size; 47.5em (760px) in this case. Below that screen size those elements are set to display: none preventing them, and their background images, from being rendered by the browser.

However the two javascript files, required for the scrolling magic to happen, are still being loaded and then fired off on the scroll event on smaller screens, although nothing is visible on screen. This is obviously way across the unacceptable line.

Solution

For a start, I found Paul Irish’s demo of matchMedia, and used it to only fire up Superscrollorama along with the same media query width used by the CSS.

The two files, tweenmax.js and superscrollorama.js, are still being loaded up unnecessarily though. Typically I include js files in WordPress using wp_register_script(), and wp_enqueue_script() and have so far been unable to have the scripts enqueued based on a media query.

My, possibly messy, solution is to include the files after the wp_footer() hook in WordPress’s footer.php, using JavaScript, so the same matchMedia check can be run. I’m using a little function to insert js files with js to help.

Which looks like this:

Trade Off

A downside to this is that the matchMedia check is only done on page load, not window resize. So if you load up the site on a browser window less then the media query width, and then increase your viewport beyond it, the JavaScripts will not be loaded, and the animations will not run.

However, from what I’ve heard, it’s only us web folk who resize every new site we land on as a first action, so I decided the reduced page weight for small screen users is an acceptable trade off for this interim solution.

JavaScript Caveat

I’m not a JavaScript master. I’m more a Google search and jQuery recipe kind of guy. So in short, I’m hoping someone will help take this apart, and show how it can be made better.

 

 

Paddy O’Hanlon is a web designer and one of the principals at Logo24. He is a lover of good semantics, well documented and architected CSS, and beautiful, content-driven design. (Really the design-guise is a cover-up so he can covertly feed his travel addiction and climb many rocks around the world). He tweets @Paddy.

Comments make us happy