⊗tlWpBsCP 2 of 55 menu

Problem with cache in browsers

The browser caches included CSS style files, JavaScript scripts and images. Caching means that the browser downloads the included files only the first time the user visits the site. On subsequent visits, these files will not be downloaded again, but will be taken from the cache browser.

Caching is useful. It is designed to increase the speed of loading a site. After all, it is faster for a browser to take a file from its storage than to download it from the Internet each time.

However, the price for speed is inconvenience during development. The thing is that if you change something in your code and then upload the changes to the hosting - all users who have already visited your site will have an old cached copy of the code.

First solution to the problem

To combat this behavior, you need to rename the modified files each time. In practice, this is not convenient, so a clever trick is used. Its essence is that when connecting a file, after the file name, we put a question mark, an equal sign, and the version number of your script. This construction is called the GET parameter.

The presence of a GET parameter in the file name does not "spoil" the path from the server's point of view, as it still points to the same file. But from the browser's point of view, changing the GET parameter makes the browser consider the path to the file as changed and download the file again.

To combat the cache, when you make changes to your code file, you will need to increase the value of the GET parameter by one. See an example of this approach:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="styles.css?v=1"> <script src="script.js?v=1"></script> </head> <body> </body> </html>

The second solution to the problem

There is a more advanced approach. It consists of adding random strings to file names, like this:

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="styles.398db7afe3b52e94bb25.css"> <script src="script.1d12c304c284a752cb9a.js"></script> </head> <body> </body> </html>

These lines are called hashes. A hash is a unique line. It is calculated from the contents of a file in a special way. This means that each text has its own unique hash. If the text of a file has been changed, then its hash will be different and we will need to change it in the file name.

Of course, manually calculating hashes and renaming files is not a fun activity. Therefore, this approach is used only if we have some tool that allows us to automatically calculate hashes and rename files, as well as change file names to new ones in HTML files. Webpack allows you to do all this. We will learn this throughout the tutorial.

enru