Cordova应用程序自动同步/更新Web内容(.js文件),如果更新版本可用,否则使用缓存版本

Cordova app to auto sync/update web content (.js files) if updated version is available, else use cached one?

本文关键字:更新 如果 新版本 版本 缓存 文件 同步 应用程序 Web js 内容      更新时间:2023-09-26

我使用标签在我的应用程序中包含一个外部.js文件。是否可以在将来使用缓存版本,直到.js的更新版本可用?

如果更新版本可用,则应用程序应使用更新的版本。

使用以下

方法使其工作:

使用文件传输.下载与标头

headers: {
            "If-Modified-Since": <last download date>
        }

例如。

   var targetPath = cordova.file.dataDirectory + "external.js"
   fileTransfer.download(
    uri,
    targetPath,
    function(entry) {
         var success = function(status) {
         var script = document.createElement("script");
         script.setAttribute("type", "text/javascript");
         script.setAttribute("id", 'addedScript1');
         script.setAttribute("src",  targetPath ;
         document.getElementsByTagName("head")[0].appendChild(script);
        }
        var error = function(status) {
            alert('Error: ' + status);
        }
        window.localStorage.setItem("last_modified", new Date(new          Date()).toGMTString());
        window.cache.clear( success, error );
    },
    function(error) {
        console.log(JSON.stringify(error));
        var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("id", 'addedScript');
        script.setAttribute("src", targetPath
        document.getElementsByTagName("head")[0].appendChild(script);
    },
    false,
    {
       headers: {
            "If-Modified-Since":  window.localStorage.getItem("last_modified")
        }
    }
);
相关文章: