Load External Script and Style Files in a SPA

蓝咒 提交于 2020-01-03 10:09:07

问题


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.


回答1:


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



回答2:


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.




回答3:


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="



来源:https://stackoverflow.com/questions/33842557/load-external-script-and-style-files-in-a-spa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!