gpt4 book ai didi

javascript - 如何在不支持 requestAnimationFrame 的浏览器中忽略 requestAnimationFrame

转载 作者:行者123 更新时间:2023-11-28 12:27:40 30 4
gpt4 key购买 nike

假设我们有一个功能/模块,可以增强网站。所以这并不是真正必要的,它使用 requestAnimationFrame,即 not supported in older browsers比如IE8/9。我可以填充 requestAnimationFrame,但由于它只是一个增强功能,旧版浏览器应该忽略它。该模块的代码看起来或多或少像这样:

;(function( window, document, undefined ) {
'use strict';

// Example Module
// @constructor
function Module( el, options ) {
// ...
}

Module.prototype = {
init: function() {
// If requestAnimationFrame is not supported, no alert should pop up
alert("init");
},

method: function() {
// If requestAnimationFrame is not supported, no alert should pop up
alert("start");
}
};

window.Module = Module;

})( window, document );

然后我可以创建一个新实例

var instance = new Module(document.getElementById('test'));

并与之“互动”

instance.init();
instance.method();

此代码的问题是,在 IE9 中会弹出错误,因为 IE9 不识别“较新”的函数,如 requestAnimationFrame。我可以添加一个 if 语句到

if ( window.requestAnimationFrame ) {
var instance = new Module(document.getElementById('test'));
}

以及我在任何地方使用它。不过,在模块中的某个位置检查 requestAnimationFrame 支持会容易得多。如果不支持,则不会发生任何事情,旧版浏览器应该忽略它。所以我尝试做类似的事情

// @constructor
function Module( el, options ) {
if ( !window.requestAnimationFrame ) {
return false;
}
//...
}

但这并不能阻止旧版浏览器执行所有方法,如“.init()”或“.method()”(在本例中)。我真的必须在每个方法中都添加这个 if 语句吗?或者我还能做些什么吗?

最佳答案

我不知道为什么,当您已经弄清楚逻辑时,您选择将其实现为注释。只需用代码替换注释即可:

Module.prototype = {
init: function() {
if(typeof requestAnimationFrame === 'undefined') return;
alert("init");
}
};

如果您愿意,也可以检查window.requestAnimationFrame

<小时/>

附加答案:

如何避免编写许多if

您可以将 if 语句封装在您自己的控制结构中。和 JavaScript 中一样,我们使用函数来实现新的“语法”:

function restricted (f) {
return function () {
if(typeof requestAnimationFrame === 'undefined') return;
return f.apply(this,arguments);
}
}

现在您可以使用 restricted(function... 而不是 function 来定义方法:

Module.prototype = {
init: restricted(function() {
alert("init");
}),

method: restricted(function() {
alert("start");
})
};

关于javascript - 如何在不支持 requestAnimationFrame 的浏览器中忽略 requestAnimationFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26297766/

30 4 0
文章推荐: php - WordPress:帖子 ID 自定义 CSS
文章推荐: html - 我的
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com