1

I'm trying add delay to window onbeforeunload script. I have a css animation for 0.3s and need 0.3s delay before unload page. Is it possible? My example code is here;

window.onbeforeunload = function (event) {
    $('.page-loader').removeClass("page-loader--hidden").addClass("page-loader--fading-in");
};
kront
  • 33
  • 1
  • 7

2 Answers2

0

Okay, what I noticed was that you are able to replicate the required CSS animation while traversing an anchor link or while refreshing/reloading a page. However, you are unable to repeat the same effect for closing the browser tab. I am guessing there are some restrictions on that.

Please refer: https://developer.mozilla.org/en-US/docs/Web/Events/unload. And, the link about beforeunload event within.

trk
  • 2,106
  • 14
  • 20
0

The answer to What are the limitation using before unload event? explains that:

The only way to guarantee your function will run to completion is to make sure you're writing synchronous code that blocks the event

In this particular example, the classes would be applied, but css transitions would most likely not show as they are completely separate to the javascript call and are not blocking.

If you would like your animations to show, then you would most likely need to either trigger a javascript function that runs for the duration of your animation but doesn't stop css animations, or change your animation over to a javascript function or library instead.

I've had success with a number of sites by using jQuery animations. In your case, it might look something similar to this:

window.onbeforeunload = function(){
    $('.page-loader').removeClass("page-loader--hidden").hide().fadeIn(300);
};
Shaun Cockerill
  • 800
  • 8
  • 11