How to Automate Cache Busting in JavaScript

Asked 2 years ago, Updated 2 years ago, 78 views

Nice to meet you.
I've been looking into many things, but it's boiling down, so I'd like to ask you a question.

We are developing using Spring in Java 8.
The JS framework is AngularJS (1 series).

What I would like to do this time is to add query strings such as dates and versions to CSS/JS that are loaded externally in HTML, but I have manually replaced them based on the release date and pushed them to the repository every time before the release.

Therefore, JavaScript would like to generate a query in yyyymmdd format so that it can be updated daily.

This is

<link href="css/bootstrap.min.css?20180510"rel="stylesheet" type="text/css"/>

I want it to automatically look like the following when it opens the next day.

<link href="css/bootstrap.min.css?20180511"rel="stylesheet" type="text/css"/>

However, since I didn't have many opportunities to touch JavaScript in my elementary school life, and I didn't know whether or not it would be possible to do so, could I ask for your advice?

If there is not enough information, I would appreciate it if you could let me know.

Sorry for the inconvenience, but I appreciate your cooperation.

javascript java html5 angularjs spring

2022-09-30 21:32

1 Answers

A string of external css tags is generated in javascript and read by document.write in the head as follows:
(It's hard to understand if it's a snippet run, so I'll put css in the letter color red.)

<head>
    <script>
        const now = new Date()
        consty="+now.getFullYear();
        constm=("00"+(now.getMonth()+1)).slice(-2);
        constd=("00" + now.getDate()) .slice(-2);
        document.write(`
            <link href="css/bootstrap.min.css?${y+m+d}"
                  rel="stylesheet"
                  type = "text/css" >
        `);
        document.write(`<style>h1{color:red;}</style>`);
    </script>
</head>
<body>
    <h1>How to Automate JavaScript Cache Busting<h1>
</body>


2022-09-30 21:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.