0

I just made loading screen with Javascript and am wondering which part of HTML Document it must be placed. I mean on inside of or before closing tag??? Some documents say it must be placed on because it has to be loaded before any contents, but it seems to work well even though I put it before .

Could you tell me which part of HTML Document I "must" or "had better" put the scripts? Is there difference in case with "defer" or "no defer"??

window.addEventListener('load', function () {
    document.querySelector('#js-loading').classList.add('hide');
});
.loading {
    opacity: 1;
    transition-property: visibility, opacity;
    transition-duration: 0.2s; 
}
.loading.hide {
    visibility: hidden;
    opacity: 0;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <link rel="stylesheet" href="css/style.css">
        <script src="js/script.js"></script> //Position A ???
        <script src="js/script.js" defer></script> //Position A with defer???
    </head>
    <body>
        <div class="loading" id="js-loading">
            <div class="loading-img"><img src="images/loading.svg" alt=""></div>
        </div>
        <div>content</div>
        <script src="js/script.js"></script> //Position B ???
        <script src="js/script.js" defer></script> //Position B with defer???
    </body>
</html>

2 Answers 2

1

The docs (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script) are saying about the defer attribute:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating.

Without the defer attribute, the scripts would be loaded immediately.

But in any case and independent of the script tag placement, the scripts will be executed before the load event is fired, so every placement is fine for a script, which adds an event listener to the load event.

Gusto-wise, I would place them in the head part, since that is much more clean, especially if you have much content in the body part.

Sign up to request clarification or add additional context in comments.

1 Comment

OK, so every placement is fine. Also your last comment was useful for me. Thank you so much!!
1

You can use document.readyState API to know when the document is completely loaded.

You can refer this answer for more insight.

https://stackoverflow.com/a/44715040/7181668

1 Comment

I didn' t know this way to check. So interesting! I really appreciate you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.