Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
How can I prevent caching when loading javascript with document.createElement('script')?

I am using a technique described by Aaron Smith on https://aaronsmith.online/easily-load-an-external-script-using-javascript/ to dynamically load Javascript code. It works fine when I first create a code file but if I change that file, the browser doesn't pick up the new version. I assume that means the code is being cached in the browser.

Here is my code, which is nearly identical to Aaron's example:

const loadScript = (src) => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.on   load = resolve;
        script.onerror = reject;
        script.src = src;
        document.head.append(script);
    });
};

How can I ensure that users always load the latest version of my code? I prefer not to change the name of the code file every time I update it. I am also not able to ask users to reconfigure their browsers to run my solution.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Simply assign a random querystring to make the browser think it's different:

const loadScript = (src) => {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.onload = resolve;
        script.onerror = reject;
        script.src = src + `?dummy=${encodeURIComponent(Math.random())}`;
        document.head.append(script);
    });
};

Every time you load the page you're loading a 'different' script.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda