Skip to content

Instantly share code, notes, and snippets.

@richarddewit
Created March 27, 2017 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richarddewit/2619126ce738d44e1144e78dbe7aa6f5 to your computer and use it in GitHub Desktop.
Save richarddewit/2619126ce738d44e1144e78dbe7aa6f5 to your computer and use it in GitHub Desktop.
// Adds 'unloading' class to `html` tag when navigating away from the page
//
// Make sure downloads open in another page with target="_blank"
// "beforeunload" is fired any time a link is clicked.
// If the link points to a file to download, the user won't be actually
// leaving the page, but beforeunload will still have fired.
(function () {
var unload = {};
unload.init = function () {
// Cache html element
unload.$html = $(document.documentElement);
// Attach event
$(window).on('beforeunload', unload.unloading);
}
unload.unloading = function (e) {
unload.$html.addClass('unloading');
// Set fallback
setTimeout(unload.failed, 5000);
}
// Useful if the user comes back, the loading fails, or it takes way too long
unload.failed = function () {
unload.$html.removeClass('unloading');
}
// Set this whole thing up on DOMready
$(unload.init);
return unload;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment