Upload external Script and Style files to SPA

I have a SPA type that uses the API to collect data. There are some examples of this SPA, and they all use a common style and script files. So my problem is that I am changing one line in these files, I have to open every instance and update the files. It really is a lot of time for me.

One approach is to put these files in a folder on the server and then change the version depending on the time, but I will lose my browser cache if I use this solution:

<link href="myserver.co/static/main.css?ver=1892471298" rel="stylesheet" /> <script src="myserver.co/static/script.js?ver=1892471298"></script> 

The value of ver is created based on time, and I cannot use the browser cache. I need a solution to update these files from the API, then all SPA systems will be updated.

+5
source share
3 answers

In the head tag, you can add the code below:

 <script type="text/javascript"> var xmlhttp = new XMLHttpRequest(); var url = "http://localhost:4000/getLatestVersion"; //api path to get the latest version xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var tags = JSON.parse(xmlhttp.responseText); for (var i = 0; i < tags.length; i++) { var tag = document.createElement(tags[i].tag); if (tags[i].tag === 'link') { tag.rel = tags[i].rel; tag.href = tags[i].url; } else { tag.src = tags[i].url; } document.head.appendChild(tag); } } }; xmlhttp.open("POST", url, false); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(); </script> 

Your api path should allow "CORS" from your site, which processes the above code. And your api should return json data as below:

 var latestVersion = '1892471298'; //this can be stored in the database var jsonData = [ { tag: 'link', rel: 'stylesheet', url: 'http://myserver.co/static/main.css?ver=' + latestVersion }, { tag: 'script', rel: '', url: 'http://myserver.co/static/script.js?ver=' + latestVersion } ]; //return jsonData to the client here 
+2
source

If you change anything in your JS or CSS, you need to update the browser cache, all you can do is update this particular version of JS, not all of them, it should reflect in the browser.

0
source

How about adding a method to the API that returns the last modified time of the files, and then pasting the value into the "src" / "href" attribute after "ver ="

0
source

Source: https://habr.com/ru/post/1236494/


All Articles