Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to show spinner until file downloads

I have a button to download an excel file. When the user clicks the button, the onClick function calls window.location= url

and when the downloading is done, the save as dialog popups with the file.

Now, I want to show a spinner until the file dialog appears. How do I do this?

I tried to create a spinner before "window.location" and hide it after that, but the spinner goes away immediately because window.location does not block until the file downloads.

Any ideas?

Thanks.

like image 359
hese Avatar asked Apr 22 '11 16:04

hese


2 Answers

It's done like this:

<script type="text/javascript">
//<![CDATA[
function download(url){
document.getElementById('spinner').style.display='';
frame = document.createElement("iframe");
frame.onload=function(){document.getElementById('spinner').style.display='none';}
frame.src=url;
document.body.appendChild(frame);
}
//]]>
</script>

In your HTML, have a spinner set up and ready to go:

<div id="spinner" style="background:url('/images/ico-loading.gif') #000 center no-repeat;opacity:.5;width:100%;height:100%;display:none;position:absolute" />

Then call it using this:

<button type="button" onclick="download('/spreadsheet.xls');">DOWNLOAD SPREADSHEET</button>

The button will call our javascript function with the URL we want to download. At this time we make the hidden spinner DIV visible and allow it take over the screen (note position absolute in style). An IFRAME is created to suck down the file. After the file downloads, it is given to the user and the .ONLOAD event is fired which hides the spinner DIV. All done with client side javascript!

like image 134
Hawk Avatar answered Nov 03 '22 01:11

Hawk


You can't do that using just client script, because there is no event for when the download completes.

You would have to download the file through a proxy page on the server, with a unique identity in the URL so that each download could be identified. Then you could send AJAX requests from the script to the server to determine the status of the download.

like image 35
Guffa Avatar answered Nov 03 '22 01:11

Guffa