【发布时间】:2014-10-10 10:53:01
【问题描述】:
假设我们有一个功能/模块,可以增强网站。所以它不是真的必要,它使用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 语句吗,或者我还能做些什么吗?
【问题讨论】:
-
这些答案对你有用吗?
-
@torazaburo 有点,接受了对我最有用的。尚未在接受的答案中看到“附加答案”部分。对不起。
标签: javascript requestanimationframe