简体   繁体   English

如何最好地预安装或预加载或缓存JavaScript库以优化性能?

[英]How best to pre-install OR pre-load OR cache JavaScript library to optimize performance?

I am working for an intranet application. 我正在为Intranet应用程序工作。 Therefore I have some control on the client machines. 因此,我对客户端计算机有一些控制权。 The JavaScript library I am using is somewhat big in size. 我正在使用的JavaScript库的大小有点大。 I would like to pre-install OR pre-load OR cache the JavaScript library on each machine (each browser as well) so that it does not travel for each request. 我想在每台机器(以及每个浏览器)上预安装或预加载或缓存JavaScript库,以使它不会针对每个请求都行进。 I know that browsers do cache a JavaScript library for subsequent requests but I would like the library to be cached once for all subsequent requests, sessions and users. 我知道浏览器的确会为后续请求缓存JavaScript库,但我希望为所有后续请求,会话和用户缓存一次该库。

What is the best mechanism to achieve this? 实现这一目标的最佳机制是什么?

You don't need access to the client machines for this. 您不需要为此访问客户端计算机。 Best practices are all serverside: 最佳实践都在服务器端:

  • GZip everything; GZip一切;
  • Minify all Javascript and CSS; 缩小所有Javascript和CSS;
  • Minimize the number of external HTTP requests. 最小化外部HTTP请求的数量。 Try to keep these to, say, 1-5 JS files, 1-5 CSS files and a few images. 尝试将它们保留为1-5个JS文件,1-5个CSS文件和一些图像。 If you have lots of images you may want to use CSS spriting ; 如果您有很多图像,则可能要使用CSS拼版
  • Version you images, CSS and Javascript; 图片版本,CSS和Javascript; and
  • Use a far futures Expires header for all images, CSS and Javascript. 对所有图像,CSS和Javascript使用远期期货Expires标头。

The last two points mean the content is cached until it changes. 最后两点表示内容将一直缓存到更改为止。 You can use an actual version number for official releases (eg jquery-1.4.2.min.js, the 1.4.2 is a version number). 您可以使用官方发行版的实际版本号(例如jquery-1.4.2.min.js,1.4.2是版本号)。 For code for your own application, often you'll use something like the mtime (last modified time) of the file as a query string. 对于您自己的应用程序的代码,通常您会使用诸如文件的mtime(上次修改时间)之类的查询字符串。 For example: 例如:

<script type="text/javascript" src="/js/code.js?1233454356"></script>

After the ? 之后? is generated from the modified time of the file. 从文件的修改时间生成。 The client downloads it once and because of the far future Expires header it won't be downloaded again until the version number changes, which won't happen until the file changes. 客户端会下载一次,并且由于将来Expires标头的缘故,在版本号更改之前它不会再次下载,而在文件更改之前不会发生。

将逻辑与JS上的执行分开,然后您可以在第一次访问用户时加载脚本(逻辑),然后使用会话/ Cookie不再加载这些文件,但是它们将在高速缓存中,然后在需要时脚本只包含它们,它们将从缓存中消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM