Magento 2 Optimization Leverage Browser Caching
Each time a user views a page on your site, the browser downloads the HTML, CSS, JS, images, fonts and any other assets required for the page to display correctly. More often than not, these assets are used on each page on your site and do not change. As an example, it's common to use a global CSS file for your whole site. Once the user has downloaded this file once, it's a waste of time downloading it again.
Browser caching allows you to tell the user's browser which files can be saved in it's cache so that the next time the file is encountered, it doesn't need to be downloaded.
Browser Caching using Mod_Expires
The most common way to leverage browser caching is to use mod_expires. The following code can be added to your .htaccess and will automatically enable browser caching for all users.
# Leverage browser caching using mod_expires # <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/pdf "access plus 1 month" ExpiresByType text/x-javascript "access plus 1 month" ExpiresByType application/x-shockwave-flash "access plus 1 month" ExpiresByType image/x-icon "access plus 1 year" ExpiresDefault "access plus 2 days" </IfModule> # End of Leverage browser caching using mod_expires #
Leverage Browser Caching using Mod_Headers
If you're on a shared server and your hosts won't enable Mod_Expires, you can still leverage browser caching by using Mod_headers, which will be available.
# Leverage browser caching using mod_headers # <IfModule mod_headers.c> <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$"> Header set Expires "Wed, 15 Apr 2020 20:00:00 GMT" Header set Cache-Control "public" </FilesMatch> </IfModule> # End of Leverage browser caching using mod_headers #
Minifying your Cached Content
Now that your assets are cached by the browser, your customer is only having to download them once. To speed this up even further, you should make that one download as small as possible. You can do this very easily in Magento by installing a Magento minify extension.