Grant Mooney Grant Mooney - 1 year ago 56
jQuery Question

Detect if link is a download in javascript/jQuery

I am working on a PHP application that can take a couple seconds to load the next page. In order to prevent users from spam-clicking buttons (and to let them know the page is loading) while the next page loads, I have implemented a page-loading spinner that covers the page:

// Assume all internal links start with ""
$('a[href*=""]').on("click", function () {
var href = $(this).attr("href");
if (!href || href[0] === "#") {
location.hash = href;// set that hash
} else {
location = href;
$(".loading-spinner").fadeIn(100, function () {
setTimeout(function(){ $(".loading-spinner").fadeOut(200); }, 10000); // 10 second loading maximum
return false;

In the event of a link starting a file download, I would like to fade out the
as soon as the download is detected.

Is there some way to detect if the link has triggered a download vs. loading a page using javascript/jQuery or do I need to specially identify all download links (using a special class, etc.)?

Answer Source

Fire an AJAX request to the URL and get the content type using the getResponseHeader function:

$.get(url, function (response, status, xhr) {
  if (xhr.getResponseHeader("content-type").indexOf("text") > -1)
    // Text based stuff.
    // Download based stuff. (eg., application/pdf, etc.)

More Info:

The XMLHttpRequest.getResponseHeader() method returns the string containing the text of the specified header, or null 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. The getResponseHeader() method returns the value as a UTF byte squence.