719-286-0751 [email protected]

Magento 2 Clear / Disable Javascript and Template Cache

Magento 2 utilizes RequireJS to load client-side assets, in both the admin and the frontend. You may have noticed, but even with your app in developer mode it still seems like the javascript and .html template files are being cached. It gets old having to clear your browser’s cache everytime you make an update to your store’s view code.

In this article, I’ll show you an easy fix to add cache busting to the RequireJS configuration, which should resolve the problem for you.

TO DOWNLOAD THE SOURCE CODE FOR THIS MODULE, SEE THE GITHUB HERE:
https://github.com/cadencelabs-master/m2cachebust

Add a module to disable RequireJS Caching

You will need to add a new module — if you download from github I’ve provided all the code you need in app/code/Cadence/CachebustYou still need to add my module to your app/etc/config.php file.
If you’d prefer to build from scratch, see this article for a tutorial on Magento 2 modules.

Everything in the attached module is just boilerplate, with the exception of one piece of code located at app/code/Cadence/Cachebust/view/frontend/requirejs-config.js. As you might guess from the name, this file is compiled into the requirejs config located at

{MAGENTO_ROOT}/pub/static/_requirejs/frontend/{package}/{theme}/{language}/requirejs-config.js

Add cache-bust param to the RequireJS Config

We’re going to add 3 lines of code to this file:

var config = {
    urlArgs: "bust=" + (new Date()).getTime()
};

That was easy! In essence, this line of code instructs RequireJS to append a bust parameter to each resource it loads. Since the parameter’s value is based on the current time, you’ll get a different value each time you load the page. Since the file name is unique, the browser (and requirejs by proxy) won’t load a cached version!

Clear the static cache

Finally (even in developer mode), you need to clear the generated static files located in

pub/static/_requirejs/frontend/{package}/{theme}/{language}

Once those files are deleted, redeploy the static assets by running the below command from your Magento 2 root:

php bin/magento setup:static-content:deploy

 

That’s it! Load up your store again, and you should see unique urls for each asset:
bust_images

 

Finally, if you want to do this for the admin as well, copy the folder structure from

Cachebust/view/frontend to Cachebust/view/adminhtml

and repeat the static cache clear.

 

Alan Barber is the Lead Web Developer at Cadence Labs and a Magento Certified developer.

1 Comment

  1. Gareth

    Does this work for .html files that are cached also?

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Install our webapp on your iPhone! Tap and then Add to homescreen.
Share This