Show 'confirm' only after loading page

2

I'm calling the following function inside the page:

window.onload = function() {
    acess();
}

function acess() {

    decision = confirm("Deseja realmente excluir o servidor cadastrado abaixo?");

    if (decision) {
        window.location.replace("fin.del.cad.php");
    } else {
        history.back();
    }
}

However, the Confirm appears and the page is left blank loading infinitely until I click on it.

I would like the Confirm and / or alert after page loading and not before. I tried some options that I saw in other forums and did not work very well.

    
asked by anonymous 02.01.2018 / 17:17

2 answers

2

You can give a delayed in the confirmation box by placing a setTimeout after .onload . A minimum value of 1 second may be sufficient (I commented the redirects for testing).

window.onload = function() {
   setTimeout("acess()",1000);
}

function acess() {

    decision = confirm("Deseja realmente excluir o servidor cadastrado abaixo?");

    if (decision) {
        // window.location.replace("fin.del.cad.php");
    } else {
        // history.back();
    }
}
Conteúdo da página
<br>
<img src="https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg"width="100">

Using readyState

The readyState will return loading until the page is fully loaded. After returning complete I still give another 1 second to execute the confirmation:

var chkReadyState = setInterval(function() {
    if (document.readyState == "complete") {
        clearInterval(chkReadyState);
        setTimeout("acess()", 1000);
    }
}, 100);
    
02.01.2018 / 17:37
1

THE DEFER ATTRIBUTE

The defer attribute tells the browser to run the script only when the HTML parsing is finished.

<script defer src="script.js">

The script will be requested asynchronously, its download will be completed, and only when the analysis of the HTML document is finished will it be executed. Even if the full script download happens before full HTML parsing, it will only run afterwards.

If you have multiple script elements with the defer attribute.

<script defer src="script.js">
<script defer src=“jquery.js">
<script defer src=“bootstrap.js">

They will be requested in parallel and executed in the declared sequence.

script.js

decision = confirm("Deseja realmente excluir o servidor cadastrado abaixo?");

if (decision) {
    window.location.replace("fin.del.cad.php");
} else {
    history.back();
}

Defer support for current browsers is great:

Credits: ASYNCHRONOUS VS DEFERRED JAVASCRIPT

    
02.01.2018 / 18:03