Google PageSpeed Tools - Insights - Optimize CSS Delivery中提供了以下片段,這表明應該使用此選項推遲加載不太重要的外部樣式表,直到初始渲染結束。加載延遲CSS後運行代碼
如何在這些CSS文件成功加載後運行一段代碼?
<html>
<head>
<style>
.blue{color:blue;}
</style>
</head>
<body>
<div class="blue">
Hello, world!
</div>
<noscript id="deferred-styles">
<link rel="stylesheet" type="text/css" href="small.css"/>
</noscript>
<script>
var loadDeferredStyles = function() {
var addStylesNode = document.getElementById("deferred-styles");
var replacement = document.createElement("div");
replacement.innerHTML = addStylesNode.textContent;
document.body.appendChild(replacement)
addStylesNode.parentElement.removeChild(addStylesNode);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
else window.addEventListener('load', loadDeferredStyles);
</script>
</body>
</html>
這個問題是問如何等待一兩件事,運行的是之前加載,這是一個交代,對專題問題 –