Media Queries and JavaScript

JS
S
JavaScript

Using <link> preloaders with media queries and executing media queries with JavaScript. https://responsivedesign.is/develop/browser-feature-support/media-queries-for-common-device-breakpoints/

1/*
2  <link rel="preload" href="bg-smallone.png" as="image" media="(max-width: 600px)">
3  <link rel="preload" href="bg-bigone.png" as="image" media="(min-width: 601px)">
4 Only of the images will be preloaded according to the user screen size.
5The browser will pre-run the media query
6*/
7
8const maxW = window.matchMedia("(max-width: 600px)"); // => MediaQueryList
9if(maxW.matches){
10     // use my smaller header image
11      header.style.backgroundImage = 'url(bg-smallone.png)';
12} else {
13    // use the big one
14      header.style.backgroundImage = 'url(bg-bigone.png)';
15}
16
17// Most used media queries for device breakpoints
18window.matchMedia("(min-device-width : 320px)"); // => MediaQueryList
19window.matchMedia("(min-width : 320px)"); // => MediaQueryList
20window.matchMedia("(max-width : 320px)"); // => MediaQueryList
21window.matchMedia("(orientation : 320px)"); // => MediaQueryList
22window.matchMedia("(-webkit-device-pixel-ratio: 3)"); // => MediaQueryList

Created on 1/12/2018