在SPA中加载外部脚本和样式文件

Sam*_*ami 6 html javascript caching single-page-application

我有一种SPA,它使用API​​来获取数据.这个SPA有一些实例,它们都使用常见的样式和脚本文件.所以我的问题是当我更改这些文件中的一行时,我将打开每个实例并更新文件.这对我来说真的很耗时.

其中一种方法是将这些文件放在服务器的文件夹中,然后根据时间更改版本,但如果我使用此解决方案,我将丢失浏览器缓存:

<link href="myserver.co/static/main.css?ver=1892471298" rel="stylesheet" />
<script src="myserver.co/static/script.js?ver=1892471298"></script>
Run Code Online (Sandbox Code Playgroud)

ver值是根据时间生成的,我不能使用浏览器缓存.我需要一个从API更新这些文件的解决方案,然后将更新所有SPA.

dee*_*nin 5

在您的 head 标签中,您可以添加以下代码:

<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>
Run Code Online (Sandbox Code Playgroud)

您的 api 路径应允许来自处理上述代码的网站的“CORS”。你的 api 应该返回如下所示的 json 数据:

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
Run Code Online (Sandbox Code Playgroud)