Leverage Browser Caching for Images, CSS and JS in WordPress via .htaccess File
We need to Leverage Browser Caching for Images, CSS and JS in a website to increase browsing speed and to achieve that in WordPress we mostly use a plugin. An Plugin can create extra overhead in terms of keeping it updated and additional maintenance for a webmaster. Caching can be achieved easily with use of .htaccess file in WordPress. Add below code in .htaccess file and upload it on root of your WordPress Installation. We are good to go without use of a plugin for this.
Steps To Leverage Browser Caching in WordPress with .htaccess
Find .htaccess File in Website Root Directory and add below code at the end of your file –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
## EXPIRES CACHING ## ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType text/css "access 1 month" ExpiresByType application/pdf "access 1 month" ExpiresByType text/x-javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 2 days" ## EXPIRES CACHING ## |
Code For Minify HTML, Javascript and CSS in WordPress without Plugin.
Find functions.php File in Website theme Directory and add below code in your file –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<!--?php class WP_HTML_Compression { // Settings protected $compress_css = true; protected $compress_js = true; protected $info_comment = true; protected $remove_comments = true; // Variables protected $html; public function __construct($html) { if (!empty($html)) { $this->parseHTML($html); } } public function __toString() { return $this->html; } protected function bottomComment($raw, $compressed) { $raw = strlen($raw); $compressed = strlen($compressed); $savings = ($raw-$compressed) / $raw * 100; $savings = round($savings, 2); return '<!--HTML compressed, size saved '.$savings.'%. From '.$raw.' bytes, now '.$compressed.' bytes-->'; } protected function minifyHTML($html) { $pattern = '/<(?<script>script).*?<\/script\s*>|<(?<br ?--> |