Defer loading of JavaScript
Overview
Deferring loading of JavaScript functions that are not called at startup reduces the initial download size, allowing other resources to be downloaded in parallel, and speeding up execution and rendering time.
Details
Like stylesheets, scripts must be downloaded, parsed, and executed before the browser can begin to render a web page. Again, even if a script is contained in an external file that is cached, processing of all elements below the script is blocked until the browser loads the code from disk and executes it. However, for some browsers, the situation is worse than for stylesheets: while JavaScript is being processed, the browser blocks all other resources from being downloaded. For AJAX-type applications that use many bytes of JavaScript code, this can add considerable latency.
For many script-intensive applications, the bulk of the JavaScript code handles user-initiated events, such as mouse-clicking and dragging, form entry and submission, hidden elements expansion, and so on. All of these user-triggered events occur after the page is loaded and the onload event is triggered. Therefore, much of the delay in the "critical path" (the time to load the main page at startup) could be avoided by deferring the loading of the JavaScript until it's actually needed. While this "lazy" method of loading doesn't reduce the total JS payload, it can significantly reduce the number of bytes needed to load the initial state of the page, and allows the remaining bytes to be loaded asynchronously in the background.
To use this technique, you should first identify all of the JavaScript functions that are not actually used by the document before the onload event. For any file containing more than 25 uncalled functions, move all of those functions to a separate, external JS file. This may require some refactoring of your code to work around dependencies between files. (For files containing fewer than 25 uncalled functions, it's not worth the effort of refactoring.)
Tip: Use the Page Speed Profile Deferrable Javascript option to automatically identify candidates for refactoring.
Then, you insert a JavaScript event listener in the head of the containing document that forces the external file to be loaded after the onload event. You can do this by any of the usual scripting means, but we recommend a very simple scripted DOM element (to avoid cross-browser and same-domain policy issues). Here's an example (where "deferredfunctions.js" contains the functions to be lazily loaded):
<script type="text/javascript">
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
分享到:
相关推荐
解决"jsp页面加载时提示loading"的问题需要从多方面进行排查和优化,包括页面内容优化、服务器性能提升、网络条件改善、代码错误检查、缓存策略调整、服务器配置优化、数据库性能优化、AJAX请求优化、JavaScript脚本...
对于JavaScript,我们要注意避免阻塞DOM解析,可以考虑使用异步加载或 defer 属性来提升页面加载速度。 最后,为了便于开发者参考和学习,项目可能提供了一个在线预览链接,如给出的"详细介绍参考 ...
1. **异步加载(Asynchronous Loading)**:JavaScript的异步特性使得我们可以在不阻塞主线程的情况下加载和执行代码。通过`<script async>`或`<script defer>`属性,我们可以实现脚本的异步或延迟加载,这可以显著...
11. **性能优化**:通过延迟加载(lazy loading)、代码分割、压缩和最小化等技术,JavaScript可以优化广告加载速度,减少对页面性能的影响。 12. **广告网络通信**:JavaScript可以与广告网络的服务器进行通信,...
2. **异步加载与SEO**:使用`async`或`defer`属性加载JavaScript可以帮助避免阻塞页面渲染,这对SEO是有益的。同时,确保重要内容在页面首屏就能被爬虫抓取。 3. **JSON-LD用于结构化数据**:JavaScript可以用来...
在网页开发中,浏览器遵循一定的规则来解析HTML、CSS和JavaScript文件,从而构建出完整的页面。本篇文章将详细探讨页面加载顺序,以及如何通过巧妙使用`loading`来优化用户体验。 首先,我们来看页面加载的基本顺序...
这可能涉及到优化图片大小、减少 CSS 和 JavaScript 代码冗余,以及利用异步加载(async 或 defer 属性)等方式。 7. **Ajax 交互**:如果页面部分内容是通过 Ajax 动态加载的,那么加载指示器可能需要在这些请求...
Vanilla JavaScript Google的类似MaterialDesign的加载模式 安装 <!-- include material lite libs --> < link rel =" stylesheet " href =" ...
- `loading`: 脚本代码载入中。 - `loaded`: 脚本代码完成读入,但尚未开始解释执行。 - `interactive`: 解释执行过程中。 - `complete`: 脚本已经执行完成。 通过监控`readyState`的变化,我们可以精确地知道何时...
4. **延迟加载和异步加载**:对于非首屏必要的JavaScript,可以使用延迟加载(lazy loading)或异步加载(async loading),这样在页面初始渲染时不会阻塞DOM,提高页面加载速度。 5. **压缩和最小化**:使用工具...
总的来说,JavaScript的加载和执行优化包括合理放置标签、利用异步和defer属性以及合并和压缩JavaScript文件,以减少HTTP请求,提高页面加载速度。开发者应当理解这些概念,以便在构建高性能网页时做出明智的选择。
- `defer` 属性适用于外部JavaScript文件,它告诉浏览器在HTML解析完成后,但在DOMContentLoaded事件触发之前执行这些脚本,按脚本在文档中的顺序执行。 3. **异步加载(Async Loading)**: - `async` 属性同样...
JavaScript是网页交互的核心,但它的执行方式可能会对页面加载速度造成影响。当用户打开一个网页时,浏览器会按顺序下载并执行所有内联和外部的JS文件,这可能导致页面渲染的延迟,尤其是在文件体积较大或者数量较多...
#### 第一章:加载与执行(Loading and Execution) **核心概念:** - **浏览器的单线程模型**:JavaScript在浏览器中执行时采取的是单线程模型,意味着在JavaScript代码执行过程中,浏览器无法进行其他任务,如...
在"page-loading"场景中,JavaScript主要负责监控和控制页面的加载状态,通过事件监听、异步加载、资源预加载等多种技术来提升页面性能。 1. **事件监听**:JavaScript通过监听`DOMContentLoaded`和`load`事件来...
4. **图片预加载**:`loading.gif`可能是一个预加载指示器,用于在页面主要内容加载之前显示,以告知用户页面正在加载。预加载可以使用JavaScript实现,预先请求图片或其他资源,以便在用户实际交互时能快速显示。 ...
异步加载(Asynchronous Loading)是JavaScript中一个重要的概念,它允许脚本在不阻塞页面渲染的情况下加载。相比于传统的同步加载,异步加载能提高网页性能,避免"阻塞渲染"现象,从而提升用户体验。 在JavaScript...