简体   繁体   中英

Load External Script and Style Files in a SPA

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.

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

如果您更改了JS或CSS中的任何内容,那么您必须更新浏览器缓存,您所能做的就是更新特定的JS版本而不是所有这些版本,它应该反映在浏览器中。

如何在API中添加一个方法,返回文件的上次修改时间,然后在“ver =”之后将值插入“src”/“href”属性中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM