简体   繁体   中英

What is the Media Query equivilent for Jquery

When my website is on a desktop-sized display, I want additional jQuery scripts to load that will not be loaded on mobile sized displays.

CSS has Media Queries which makes it easy to load CSS files depending on browser size. Is there an equivalent of this for Jquery?



Background Research:

Here are some solutions I have found and the drawbacks of each.

Solution 1: Enquire.js - This is supposed to be the media query equivalent for Javascript (I think). However, the documentation isn't very clear (at least for a beginner).

For example, this tutorial gives the following example:

enquire.register("max-width: 960px", function() {
  // put your code here
});

However, if you copy and paste Jquery code where it says, nothing happens! I think you might have to place a link to your Jquery file, but the documentation doesn't explain how to do that!

Solution 2: Use Window Resize - You can use $(window).resize to trigger scripts. However, it will only work if the user re-sizes the browser. This is no good for a desktop user whose window is always maximized.

A further problem is that the script will be loaded each time the browser is re-sized. This can be a problem for some scripts (see the example here where the words false/true are repeated endlessly if the window is resized several times).

Solution 3: Set a hidden 100% width DIV and then run a script that checks it's width - The drawback of this is that it only runs when the page first loads, so it's not good for a user who changes the size of their window (or orientation of the device). You can run a timer so it checks the width every 1 second, but that doesn't seem very efficient.

Does anyone know of solutions that works?

Thanks.

PS. This question is about a Media Query equivalent for Jquery. It is NOT about trying to recreating CSS Media Queries in Javascript (ie it is NOT about using Jquery to load different CSS files for different window sizes which is achieved with css3-mediaqueries-js ).

While it isn't specifically for jQuery, I've had high levels of success with Paul Irish's Modernizr library. A simple method allows you to test for media queries using the same syntax as you would in CSS. The tests return either true or false. For example:

if (Modernizr.mq('only screen and (max-width: 768px)') == true) {
  // your code here
} 

If the browser would accept CSS from that rule, then the function would return true as well. You can read more in the Modernizr docs .

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM