Load External Script and Style Files in a SPA

2019-06-20 08:33发布

I have a type of SPA which consumes an API in order to fetch data. There are some instance of this SPA and all of them use common style and script files. So my problem is when I change a single line in those files, I will have to open each and every instances and update the files. It's really time consuming for me.

One of the approaches is to put those files in a folder in the server, then change the version based on the time, but I will lose 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 ver value is produced based on time and I cannot use browser cache. I need a solution to update these files from the API, then all of the SPAs will be updated.

3条回答
Ridiculous、
2楼-- · 2019-06-20 09:08

In your 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 website that handles the code above. And your api should return a json data like 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
查看更多
三岁会撩人
3楼-- · 2019-06-20 09:08

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

查看更多
爷的心禁止访问
4楼-- · 2019-06-20 09:11

How about adding a method in your API returning the files' last modified time and then inserting the value into the "src"/"href" attribute after the "ver="

查看更多
登录 后发表回答