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>
Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
abms
  • 545
  • 1
  • 3
  • 13

2 Answers2

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.

Peter Lehnhardt
  • 4,375
  • 1
  • 14
  • 33
  • OK, so every placement is fine. Also your last comment was useful for me. Thank you so much!! – abms Apr 15 '19 at 11:43
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

reflexgravity
  • 910
  • 10
  • 17