如何在浏览器调整大小时最有效地检查某些 "breakpoints"?

How to most efficiently check for certain "breakpoints" upon browser re-size?

我正在玩一些定义了两个断点的响应式设计:

Mobile > max-width 320px
Tablet portrait > max-width 767px

在桌面上,我有很多动画 + 高级功能 Javascript。在手机和平​​板电脑上,我希望简化和禁用一些 JS + "re-building" 一些 DOM 元素。

我想知道确定某些断点(根据宽度)的最有效方法是什么?我在这里考虑了很多关于性能的问题。

我知道我可以在调整大小时简单地检查 window 宽度,例如:

$( window ).resize(function() {
  if ($(window).width() > 320 && $(window).width() < 400) {
    //mobile
  }
  if ($(window).width() > 401 && $(window).width() < 768) {
    //tablet
  }
  if ($(window).width() > 769) {
    //desktop
  }
});

但这似乎是一个非常 "expensive" 的操作?

也非常欢迎对可用于此的轻量级库提出任何建议!

我经常运行遇到这个问题,还没有找到完美的解决方案。但是,有一种似乎不那么耗费资源的解决方法。通过在 resize() 函数中使用超时并不断清除它,一旦视口停止调整大小,您可以确保您的代码仅为 运行。

var resizeTimer, width;
var mobile = tablet = desktop = false;

$(window).resize(function() {
    // clear the timeout
    clearTimeout(resizeTimer);

    // execute breakpointChange() once the viewport 
    // has stopped changing in size for 400ms
    resizeTimer = setTimeout(breakpointChange(), 400);
});

function breakpointChange() {
    // use vanillajs window.innerWidth 
    // instead of jQuery $(window).width() as suggested by simon
    width = window.innerWidth;

    if (!mobile && width < 400) {
        tablet = desktop = false;
        mobile = true;
        console.log('is mobile');
    }

    if (!tablet && width > 401 && width < 768) {
        mobile = desktop = false;
        tablet = true;
        console.log('is tablet');
    }

    if (!desktop && width > 769) {
        mobile = tablet = false;
        desktop = true;
        console.log('is desktop');
    }
}
$(window).resize();

这当然不是最好的,但它可以防止您的代码经常成为运行。请随意添加到我的答案 and/or 纠正我。这是一个fiddle

当你停止使用 jQuery 时它会非常高效,因为它已经过时了。 JavaScript window 对象具有 innerWidth / outerWidth 属性,您无需 jQuery 调用即可使用。

$( window ).resize(function() {
  var width = window.innerWidth; // e.g.

  if (width > 320 && width < 400) {
    //mobile
  }
});

所以您没有任何性能问题,因为这只是一个对象的 属性,没有函数调用/强制转换。如果您确实需要了解设备,这将是完美的解决方案。

当您在内部使用 DOM 操作时 - 按照 "The F"

的建议查找超时