We have a javascript installed in our client website (sdk.js , sort of like Google Analytics tracking code), and the javascript file has 30 days cache time(max-age) for bandwidth saving purpose. Every time we have released a new javascript, how can we make the script refresh it self?
Here is what I thought: First, the client has installed our javascript file:
<script type="text/javascript" src="https://cdn.exampleAPI.com/js/sdk.js" async></script>
In the script, it will fetch our backend API, then the API response with a 'latest_sdk' field, and the cached script will compare it with current local sdk.js version and decide to refresh the cached js or not, will this work? Or any other solution?
const LOCAL_SDK_VERSION = '0.1';
fetch('https://exampleAPI.com')
.then(response => response.json())
.then(data => {
var latestSDK = data.info[0].latest_sdk;
if (LOCAL_SDK_VERSION < latestSDK) {
console.log('New version SDK available: ' + latestSDK);
var newSDK = document.createElement('script');
newSDK.src = 'https://cdn.exampleAPI.com/js/sdk.js?v=' + latestSDK;
document.head.appendChild(newSDK);
})
.catch(error => console.error('catch error:', error));
P.S. Since the script was installed in our client website, we can Not force to refresh/or modify the page.