简体   繁体   中英

Cache combined javascript files individually

Is it possible to cache JavaScript files individually even if they are combined into a single JavaScript file?

I need this because I would like to have both advantages of caching the downloaded content and combining the data sent over the internet.

Browser specific solutions will also be very appreciated!

Yes, Angular does something similar in fact. The trick is to cache at a different level and not the HTTP protocol level. You cache it yourself caching to localStorage or indexeddb.

Create a cache object, and whenever you add a file, put it there

// a.js, this file generated by a readFile call in nodejs or whatever
// build process you want to have
var cache = cache || {}; // might also want to use an array here to preserve order
cache["a.js"] = "your real a.js file as code";

A one file request can simply contain these four lines repeated for every file you want to cache, versioning is also probably appropriate here.

Next, at the end of your body section you can put

// let's say you need in this particular page a.js b.js
eval(cache["a.js"]); // write a helper function for this, remember
eval(cache["b.js"]); // cache is for example localStorage with a prefix
eval(cache["c.js"]);

Take a look at gulp . and gulp-concat specifically.

This code reads all my .js source files:

  // Make sources.  Uglify, Concat, and add hash if necessary
  // Determine output file.  Only used if config.concat === true
  var destJs = 'app' + (config.minify?'.min':'') + '.js';
  var appJs = gulp.src([config.dashboard.js, '!/src/dashboard/vendor/'])
  .pipe(plugins.plumber())
  .pipe(plugins.ngAnnotate())
  .pipe(plugins.angularFilesort())
  .pipe(plugins.if(config.minify, plugins.uglify()))
  .pipe(plugins.if(config.concat, plugins.concat(destJs)))
  .pipe(plugins.if(config.hash, plugins.hash()))
  .pipe(gulp.dest(config.dashboard.dest + '/js'))
  • plugins.ngAnnotate() annotates angular's dependency injections
  • plugins.angularFilesort() sorts them by dependency
  • plugins.if() conditionally uglifies them with plugins.uglify()
  • plugins.if() conditionally concats them with plugins.concat()
  • plugins.if() conditionally hashes them with plugins.hash() for cache-busting.
  • then writes all the files (or just one) to my projects build/js folder.

var plugins = require('gulp-load-plugins')(); loads up plugins.

There's alot here, but it's really pretty simple once you get into it. Way easier than grunt or make in my experience.

To your question, you can gulp.dest() in multiple places in the pipe()'s. Before and after minification/concatenation.

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