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

时间:2014-05-02 23:02:32

标签: javascript jquery css

我有以下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');
}

1 个答案:

答案 0 :(得分:1)

听起来你想要观看窗口调整大小的事件呢?像这样:

$(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而不是手动注入脚本元素。

我看到那里的一些代码似乎在观察窗口的高度和宽度来实现自定义窗口调整大小事件。但这并不是必需的。我认为你特别不想在这样的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');
  }
}