简体   繁体   中英

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

I am working for an intranet application. Therefore I have some control on the client machines. The JavaScript library I am using is somewhat big in size. 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. 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.

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;
  • Minify all Javascript and CSS;
  • Minimize the number of external HTTP requests. Try to keep these to, say, 1-5 JS files, 1-5 CSS files and a few images. If you have lots of images you may want to use CSS spriting ;
  • Version you images, CSS and Javascript; and
  • Use a far futures Expires header for all images, CSS and Javascript.

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). For code for your own application, often you'll use something like the mtime (last modified time) of the file as a query string. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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