4

A brief introduction

First of all, I know, the question is often asked and I have read many discussion before asking. Tipical approches to handle the cache problem that are suggested in other question are:

  1. Versioning js files in this way: <script src="/myJavascript.js?version=4"></script>. See Keparo's answer here.
  2. Create a rewrite rule on the web server in this way: RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]. See Kip's answer here.

Context description

Currently I'm refactoring my old php code running on apache2, introducing an heavy layer of js/jquery to handle the frontend and decoupling FE and BE building some api.

The js project is organized in this way:

my-project/
├── main.js
├── main.css
├── main.php
├── js/
│   ├── JsClass1.js
│   └── JsClass2.js
└── src/
    └── php_code/
        ├── class1.php
        └── class2.php

My problem

I don't know how to avoid that js classes are cached from web browser because the previous solution describer in the description are not feasible. Just to make a brief example of my problem this is a portion of code that gives me problems:

main.js

//Import my js classes
import JsClass1 from './js/JsClass1.js';
import JsClass2 from './js/JsClass2.js';

//Instantiate js objects
const j1 = new JsClass1();
const j2 = new JsClass2();

//Use js object
j2.do_stuff();
j2.do_stuff();

JsClass1.js

import JsClassN from "./JsClassN.js";

export default class JsClass1 {
    constructor(var1) {
        //Create stuff
    }

    do_stuff() {
        //Doing real stuff
    }
        
}

main.php

<!DOCTYPE html>
<html lang='it-IT'>
<head>
    <script type='module' src='/main.js?ver=<? echo  getVersion(); ?>' type='text/javascript'></script>
</head>
<body>
...
</body>

Wrap up

How can I handle those js imports and avoid that browser caches old classes when I release in production new versions? Do I need to reorganize my code structure to achieve this? And if so, what's the best approach?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Timmy
  • 693
  • 2
  • 8
  • 26

0 Answers0