javascript alert block page loads

2019-04-24 09:02发布

问题:

My client wishes to show an alert when entering a web page.

However, an alert blocks further loading of the page until "Ok" is clicked, and the page needs to load in the background while the alert is displayed.

One solution would be to use a custom alert using HTML and CSS, but this is not answering the client's needs.

Is there a solution using 'core javascript' or jQuery to allow the page to load while the alert is displayed? Thanks.

回答1:

You should run it through a setTimeout:

setTimeout(function() { alert('hello world'); }, 1);

This is shown here: Is there a JavaScript alert that doesn't pause the script?



回答2:

EDIT

see @FunKy's answer for a workaround in Firefox. (really interesting!)


Simple answer is no, it's not possible!

Reason is native alert() dialog is UI blocking and javascript is a single thread language.

You have to use a customized dialog message.

But, if some ajax request are done just before blocking UI, when alert() dialog is closed, the ajax response will/should be available. So, you still can make some ajax request just before showing alert.



回答3:

You can use a custom dialog box instead of an alert box (which block page load). For exemple, Jquery UI Dialog is easy to use (but there are many plugins which do exactly the same thing).



回答4:

show alert when page is load complete. here an example with jquery

$(function() {
    alert("foo");
});