Jump to content

Some ideas for asset optimization & preprocessing


init2null
 Share

Recommended Posts

I've gotten a little obsessed with the page loading time on my latest website. Many of you use AIOM for asset preprocessing, but I decided to use Grunt and htaccess for more control and a lighter server burden. Here are the techniques I used in a random order:

For file versioning, I supply distant expiration dates and use this line in my htaccess: RewriteRule ^([^.]+)\.[0-9]+\.([^.]+)$ $1.$2 The file is referenced as "myfile.<?php echo filemtime("myfile.js"); ?>.js", though I do this in a function for additional path translation. MD5 would be another option, but it would take longer.

For both Javascript & CSS (first converted from LESS), I first combine the multiple support libraries into one file. I include these files on the server as *.src.*; the templates includes the *.src.* files when the viewer is superuser. I then minify them and include them as *.min.*. I use Grunt to compress them all as *.*.gz and serve them as needed:

<IfModule mod_headers.c>
	# Serve gzip compressed CSS files if they exist and the client accepts gzip.
	RewriteCond %{HTTP:Accept-encoding} gzip
	RewriteCond %{REQUEST_FILENAME}\.gz -s
	RewriteRule ^(.*)\.css $1\.css\.gz [QSA]
	# Serve gzip compressed JS files if they exist and the client accepts gzip.
	RewriteCond %{HTTP:Accept-encoding} gzip
	RewriteCond %{REQUEST_FILENAME}\.gz -s
	RewriteRule ^(.*)\.js $1\.js\.gz [QSA]
	# Serve correct content types, and prevent mod_deflate double gzip.
	RewriteRule \.js\.gz$ - [T=text/javascript,E=no-gzip:1]
	RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
	<FilesMatch "(\.js\.gz|\.css\.gz|\.svgz)$">
		# Serve correct encoding type.
		Header set Content-Encoding gzip
		Header set Precompressed true #for debugging
		# Force proxies to cache gzipped & non-gzipped css/js files separately.
		Header append Vary Accept-Encoding
	</FilesMatch>
</IfModule>

I needed to provide the main script with arguments but wanted to load the Javascript using the async keyword, so I assigned the arguments as global variables and access them when JS finishes loading.

I found many ways to use SVG in this design, and I aggressively optimized the illustrations and the generated code. Editing the XML by hand can shave several kilobytes off the file. In one case, I reduced the file size from 40 KB to 4. I also use Grunt to pre-compress it as with the JS and CSS. If you're really obsessive, you can rearrange the SVG attributes for better compression.

These may be basic tips for most of you, but I'm hoping they'll be helpful to someone. For anyone interested, I've attached the Gruntfile. I only ask that you don't judge the file structure too harshly.

Since I probably haven't scratched the surface here, feel free to provide any of your own tips.

gruntfile.js.txt

  • Like 5
Link to comment
Share on other sites

 Share

×
×
  • Create New...