gpt4 book ai didi

javascript - Google 的带有 requestAnimationFrame 的示例函数 - 解释?

转载 作者:行者123 更新时间:2023-11-28 04:04:06 25 4
gpt4 key购买 nike

我遇到了谷歌提出的一个奇怪的功能。它看起来像是某种文档准备功能。我无法理解它。

谁能解释一下吗?

var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;

if (raf) raf(function() { window.setTimeout(someInitFunction, 0); });

else window.addEventListener('load', someInitFunction);

Google 开发者网站上提议了此功能:https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery

最佳答案

首先它将 requestAnimationFrame 函数分配给一个变量;

var raf = requestAnimationFrame || mozRequestAnimationFrame || webkitRequestAnimationFrame || msRequestAnimationFrame;

然后它将检查它是否存在(由浏览器实现)

if (raf){
// requestAnimationFrame is available to use
// we can use it directly or by the reference
// raf(someCallback) or requestAnimationFrame(someCallback) both equal
}else{
/* requestAnimationFrame is not implemented thus can't be used */
}

true情况下,它将使用requestAnimationFramesomeInitFunction推送到RAF执行时回调队列的最末尾(毕竟要执行主要任务和回调)

情况下;这意味着 requestAnimationFrame 不是原生实现的,它将回退到使用旧式方法在窗口的“load”事件上运行 someInitFunction

<小时/>

花点时间调查一下此代码段的执行顺序;

Run it multiple times, ideally in different browsers. "sync raf" sometimes printed after all main queue's task (after "a"); Most of the times printed after all main queue's tasks and callbacks ( right before "async raf");

Notice that "async raf" is always the latest thing to run in any situation, any browser;

function a () { console.log("a") }
function b () { console.log("b") }
function c () { console.log("c") }
//same as others, but with the settimeout hard-coded
var d = function () {
setTimeout(()=>console.log("d"),0)
}


a();
setTimeout(b,0);
requestAnimationFrame(()=>{
setTimeout(()=>console.log("async raf"),0);
console.log("sync raf")
});
setTimeout(c,0);
d();

关于javascript - Google 的带有 requestAnimationFrame 的示例函数 - 解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46856919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com