【问题标题】:How to check if a dynamically created file exists on AWS S3 using JS如何使用 JS 检查 AWS S3 上是否存在动态创建的文件
【发布时间】:2016-05-08 01:59:42
【问题描述】:

我有一个服务器端脚本,它在给定的 url 具有 1 个页面视图后在 s3 存储桶中动态创建一个 js 文件。服务器端脚本每 1 分钟运行一次。

在网站上的任何给定 URL 上,我都有一个脚本试图调用这个动态创建的文件。

如:

var host = window.location.host;
var pathName = window.location.pathname;
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.src="https://s3.amazonaws.com/some_bucket/"+host+pathName+".js;
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
})();

问题在于,如果在站点上创建了一个新 URL,并且第一个访问者访问了该页面,那么 cron 作业就有机会运行,因此存储桶中还不存在 js 文件。这会导致 404 错误,但也会导致上面的页面 javascript 发生错误,导致包含它的 js 库崩溃。

有没有办法动态检查文件是否存在,如果动态创建的文件尚未构建,则默认使用不同的文件?

例如(伪代码):

try{
   script.src="https://s3.amazonaws.com/some_bucket/"+host+pathName+".js;
}
catch(e){
   404error = true;
}
finally{
   if(404error == true){
      script.src="https://s3.amazonaws.com/some_bucket/DEFAULT.js";
   }
}

更新了代码,在出错时调用了不同的文件。这成功调用了另一个文件,但它仍然会导致 Chrome 中的 404 错误。

var host = window.location.host;
var pathName = window.location.pathname;
var script = document.createElement('script');
script.async = true;
script.type = 'text/javascript';
script.onerror = function(){
   var host = window.location.host;
   var pathName = window.location.pathname;
   var script = document.createElement('script');
   script.async = true;
   script.type = 'text/javascript';
   script.src="https://s3.amazonaws.com/some_bucket/some_default_file.js";
   var node = document.getElementsByTagName('script')[0];
   node.parentNode.insertBefore(script, node);
}
script.src="https://s3.amazonaws.com/some_bucket/"+host+pathName+".js;
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(script, node);
})();

【问题讨论】:

    标签: javascript amazon-s3 http-status-code-404


    【解决方案1】:

    使用script.onerror:

    var pathName   = window.location.pathname;
    var script     = document.createElement('script');
    script.async   = true;
    script.type    = 'text/javascript';
    script.onerror = function() {
      console.log('script failed to load');
    };
    script.src     = "https://s3.amazonaws.com/some_bucket/" + host + pathName + ".js";
    var node       = document.getElementsByTagName('script')[0];
    node.parentNode.insertBefore(script, node);
    

    【讨论】:

    • 我试了一下,但 Chrome 仍然抛出 404。在 onerror 函数中,我尝试重新运行脚本,成功调用默认文件,但仍然抛出 404。跨度>
    • 我不确定我明白你在说什么。您无法避免 404 发生,但您可以检测到它并加载另一个资源。
    猜你喜欢
    • 2019-03-16
    • 1970-01-01
    • 2018-01-23
    • 2023-03-14
    • 1970-01-01
    • 2021-08-14
    • 2015-07-27
    • 2012-08-10
    • 2018-08-01
    相关资源
    最近更新 更多