在SPA中加载外部脚本和样式文件 [英] Load External Script and Style Files in a SPA

查看:72
本文介绍了在SPA中加载外部脚本和样式文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种SPA,它使用API​​来获取数据。这个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>

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

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>

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

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

这篇关于在SPA中加载外部脚本和样式文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆