我正在开发一个 PHP 应用程序,该应用程序可能需要几秒钟才能加载下一页。为了防止用户在下一页加载时垃圾点击按钮(并让他们知道页面正在加载),我实现了一个覆盖该页面的页面加载微调器:
// Assume all internal links start with "http://www.example.com"
$('a[href*="http://www.example.com"]').on("click", function () {
var href = $(this).attr("href");
if (!href || href[0] === "#") {
location.hash = href;// set that hash
return;
} else {
location = href;
$(".loading-spinner").fadeIn(100, function () {
setTimeout(function(){ $(".loading-spinner").fadeOut(200); }, 10000); // 10 second loading maximum
});
}
return false;
});
如果链接开始文件下载,我希望在检测到下载后立即淡出.loading-spinner
。
是否有某种方法可以检测链接是否触发了下载与使用 javascript/jQuery 加载页面,还是我需要专门识别所有下载链接(使用特殊类等)?
最佳答案
向 URL 发起 AJAX 请求并使用 getResponseHeader
获取内容类型功能:
$.get(url, function (response, status, xhr) {
if (xhr.getResponseHeader("content-type").indexOf("text") > -1)
// Text based stuff.
else
// Download based stuff. (eg., application/pdf, etc.)
});
更多信息:
The
XMLHttpRequest.getResponseHeader()
method returns the string containing the text of the specified header, ornull
if either the response has not yet been received or the header doesn't exist in the response. If there are multiple response headers with the same name, then their values are returned as a single concatenated string, where each value is separated from the previous one by a pair of comma and space. ThegetResponseHeader()
method returns the value as a UTF byte squence.
关于javascript - 检测链接是否是 javascript/jQuery 中的下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383600/