有条件地加载js文件与屏幕宽度

conditionally load js file with screen width

本文关键字:屏幕 文件 加载 js 有条件      更新时间:2023-09-26

我有下面的java脚本,它根据分辨率和js文件加载屏幕。但是我必须刷新浏览器来重新加载每个分辨率的js文件,否则它会保留最后一个分辨率的js文件。

请帮助我了解如何同时加载这两个文件。

window.requestAnimFrame = (function(){
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); };
})();
var width = screen.width,
    height = screen.height,
    checkScreenSize = function () {
        if (screen.width !== width || screen.height !== height) {
            width = screen.width;
            height = screen.height;
            $(window).trigger('resolutionchange');
        }
    };
(function loop(){
  requestAnimFrame(loop);
  checkScreenSize();
})();
function includeJS(incFile) {
document.write('<script type="text/javascript" src="'+ incFile+ '"></scr' + 'ipt>');
}
if (window.matchMedia("only screen and (min-width: 1240px) and (max-width: 1280px)").matches) {
    includeJS('changer/js/changer-1280.js');
} else if (window.matchMedia("only screen and (min-width: 1390px) and (max-width: 1440px)").matches) {
    includeJS('changer/js/changer-1440.js');
} else if (window.matchMedia("only screen and (min-width: 1441px) and (max-width: 1441px)").matches) {
    includeJS('changer/js/changer-1441.js');
}

听起来你可能想看窗口大小调整事件?像这样:

$(window).on('resize', function() {
  if (window.matchMedia("only screen and (min-width: 1240px) and (max-width: 1280px)").matches) {
    $.getScript('changer/js/changer-1280.js');
  } else if (window.matchMedia("only screen and (min-width: 1390px) and (max-width: 1440px)").matches) {
    $.getScript('changer/js/changer-1440.js');
  } else if (window.matchMedia("only screen and (min-width: 1441px) and (max-width: 1441px)").matches) {
    $.getScript('changer/js/changer-1441.js');
  }
});

既然你正在使用jQuery,你可以使用它的$.getScript而不是手动注入script元素。

我看到有一些代码在那里,似乎观察窗口的高度和宽度实现自定义窗口调整大小事件。但这并不是必要的。我想你尤其不想在RAF循环中这样做,因为它可能会在每一帧中触发布局。

每次窗口的调整大小事件触发时运行那些matchMedia检查也会阻碍调整大小的性能,所以你应该在调整大小暂停后才处理这个事件。像这样:

var resizeTimer;
$(window).on('resize', function() {
  clearTimeout(resizeTimer);
  // Wait half a second before reacting to the resize event,
  //  in case the user is still actively resizing the window.
  resizeTimer = setTimeout(handleWindowResize, 500);
});
function handleWindowResize() {
  if (window.matchMedia("only screen and (min-width: 1240px) and (max-width: 1280px)").matches) {
    $.getScript('changer/js/changer-1280.js');
  } else if (window.matchMedia("only screen and (min-width: 1390px) and (max-width: 1440px)").matches) {
    $.getScript('changer/js/changer-1440.js');
  } else if (window.matchMedia("only screen and (min-width: 1441px) and (max-width: 1441px)").matches) {
    $.getScript('changer/js/changer-1441.js');
  }
}