【发布时间】: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