延迟 JavaScript 加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7272110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deferring JavaScript loading
提问by steveo225
I have heard and read a few articles about deferring JavaScript loading and am very interested. It seems to be very promising for web apps that may be useful on Mobile platforms where the amount of JavaScript that can be loaded and executed is limited.
我听说并阅读了一些关于延迟 JavaScript 加载的文章,并且非常感兴趣。对于在可加载和执行的 JavaScript 数量有限的移动平台上可能有用的 Web 应用程序来说,这似乎非常有前途。
Unfortunately, most of the articles talk about this at an extremely high level. How would one approach this?
不幸的是,大多数文章都在非常高的水平上讨论了这一点。人们将如何处理这一问题?
EDIT
编辑
Normally, all JavaScript is loaded on page load, however, there may be functions that are not necessary until a certain action occurs, at which time, the JavaScript should be loaded. This helps ease the burden of the browser on page load.
正常情况下,所有的 JavaScript 都是在页面加载时加载的,但是,可能有一些函数是不需要的,直到某个动作发生时,才应该加载 JavaScript。这有助于减轻浏览器在页面加载时的负担。
Specifically, I have a page that very heavily uses JavaScript. When I load the page on my phone, it won't load properly. As I debugged the page, I eliminated some of the JS functions. Once enough was eliminated, the page suddenly worked.
具体来说,我有一个大量使用 JavaScript 的页面。当我在手机上加载页面时,它无法正确加载。在调试页面时,我删除了一些 JS 功能。一旦消除了足够多,页面就会突然起作用。
I want to be able to load the JS as needed. And possibly even eliminate the functions simply used for start up.
我希望能够根据需要加载 JS。甚至可能取消仅用于启动的功能。
采纳答案by Sean Vieira
The basics are simple - breaking up your JavaScript code into logically separate components and loading only what you need. Depending on what you are building you can use:
基础很简单 - 将您的 JavaScript 代码分解为逻辑上独立的组件并仅加载您需要的内容。根据您正在构建的内容,您可以使用:
Loaders:
装载机:
- Modernizr.load(or yepnope.jsby itself)
- LABjs
- Many, many, manyother deferred loading libraries.
- Modernizr.load(或yepnope.js本身)
- 实验室
- 许多,许多,许多其他延迟加载库。
Dependency managers (which are alsoloaders):
依赖管理器(也是加载器):
- Require.js
- dojo.require
- JavaScript MVC's steal.js
- Several other dependency management libraries.
- 要求.js
- 道场.require
- JavaScript MVC的steal.js
- 其他几个依赖管理库。
These tools make use of a wide variety of techniques to defer the loading of scripts, the executionof scripts, manage dependencies, etc. What you need depends on what you are building.
这些工具利用多种技术来延迟脚本加载、脚本执行、管理依赖等。您需要什么取决于您正在构建什么。
You may also want to read through this discussionto learn something more about the pros and cons of using such techniques.
您可能还想通读此讨论以了解更多有关使用此类技术的利弊的信息。
Response to edit:
回复编辑:
There isn't really a good way to unloadJavaScript that you have already loaded - the closest approximation you can get is to keep all of your loading code namespaced inside your application's namespace and then "clean up" by setting that namespace, and all references to it to null
.
卸载已经加载的 JavaScript并没有真正的好方法- 您可以获得的最接近的近似值是将所有加载代码命名空间保存在应用程序的命名空间内,然后通过设置该命名空间和所有引用来“清理”到它到null
。
回答by Michelangelo
I have used a simple script published on line with some modification done by me. Assume that your COMPRESSED Javascript file is in the cache directory in your webserver and you want to defer the loading of this compressed js file.
我使用了一个在线发布的简单脚本,并进行了一些修改。假设您的 COMPRESSED Javascript 文件位于您的网络服务器的缓存目录中,并且您希望推迟加载这个压缩的 js 文件。
Your compressed js file:
您的压缩 js 文件:
80aaad2a95e397a9f6f64ac79c4b452f.js
This is the code html code:
这是代码html代码:
<script type="text/javascript" src="/resources/js/defer.js?cache=80aaad2a95e397a9f6f64ac79c4b452f.js"></script>
This is the defer.js file content:
这是 defer.js 文件内容:
(function() {
/*
* http://gtmetrix.com/
* In order to load a page, the browser must parse the contents of all <script> tags,
* which adds additional time to the page load. By minimizing the amount of JavaScript needed to render the page,
* and deferring parsing of unneeded JavaScript until it needs to be executed,
* you can reduce the initial load time of your page.
*/
// http://feather.elektrum.org/book/src.html
// Get the script tag from the html
var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];
// Get the querystring
var queryString = myScript.src.replace(/^[^\?]+\??/,'');
// Parse the parameters
var params = parseQuery( queryString );
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = '/cache/' + params.cache; // Add the name of the js file
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
function parseQuery ( query ) {
var Params = new Object ();
if ( ! query ) return Params; // return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) continue;
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}
})();
I would like to say thanks to http://feather.elektrum.org/book/src.htmlthat helped me to understand how to get the parameters from the script tag.
我要感谢http://feather.elektrum.org/book/src.html帮助我了解如何从脚本标签中获取参数。
bye
再见
回答by Spycho
Here's a useful articleon the script element's defer and async attributes. Specifying these attributes will get the browser to defer loading in different ways. You can also load in an external script using JavaScript after page load.
这是一篇关于 script 元素的 defer 和 async 属性的有用文章。指定这些属性将使浏览器以不同的方式延迟加载。您还可以在页面加载后使用 JavaScript 加载外部脚本。
It should also be noted that the position of your script elements within your HTML document will determine load and execution order if neither defer nor async have been specified.
还应该注意的是,如果既未指定 defer 也未指定 async,则 HTML 文档中脚本元素的位置将决定加载和执行顺序。
回答by Layke
Deferring loading til when? The reason typically why JS is loaded last, is so that the entire DOM has been loaded first.
推迟加载到什么时候?通常最后加载 JS 的原因是整个 DOM 首先加载。
An easy way is to just use
一个简单的方法是使用
<body onload="doSomething();">
So you could easily have doSomething()
function to load all your JS.
因此,您可以轻松拥有doSomething()
加载所有 JS 的功能。
You can also add a function to window.onload
, like
您还可以向 中添加函数window.onload
,例如
window.onload = function(){ };
Also, if you are using JS librarys, such as jQueryand Dojo, they each have their own onReadyand addOnLoad
methods in order to run some JS only after the document has already loaded.
此外,如果您使用 JS 库,例如jQuery和Dojo,它们每个都有自己的onReady和addOnLoad
方法,以便仅在文档加载后运行一些 JS。