I added <div>
that displays "loading" image into the <body>
tag. It looks cool, but unfortunately the loading div and image will only appear on screen after most of loading process is already done, after scripts and css links are loaded or at least started loading. This is probably because body is located under the <head>
tag, and not even parsed before the head is started loading. Can I display the loading div/image from the top of the document, in the head tag? I tried to add <script>
and then creatElement()
and appendChild()
but there is no body
yet to append a child. What can be done to make the loading div/image be displayed earlier?
You have to cover the complete page with your animation / text to not display the other things which are loading.
All the other js stuff (except of external sources) goes into the $(document).ready();
function.
The animation in the following snippet is going to execute when window
is ready.
$(window).ready(function() { $('#untilContentLoads').hide(); });
#untilContentLoads { position: absolute; width: 100%; height: 100%; /* background: url() no-repeat center; <-- use that for some kind of gif/svg animation */ }
<div id="untilContentLoads">Loading</div>
As @Meirion mentioned, put your script tags at the end. But also, might I suggest making the loading image a background image of the body? You can always toggle it if needed with a class on the body.
If you want to do this quickly you may want to add your script at the end of the body tag like so
<html>
<head>
</head>
<body>
<div id="loading"/>
<script>
/*Here your code will have a notion of what is loading*/
</script>
</body>
Another approach that you may want to take is to make use of body.onload script option. Following the same example
<html>
<head>
</head>
<body onload="functionForLoading()">
<div id="loading"/>
</body>
</html>
The html document needs to be parsed in order to figure out how to display it so you wont be able to interact with the body (the visible bit) until it has been read and the DOM created.
However you can specify CSS in your header which will be fast to apply to the DOM once it is loaded.
If you want the fastest appearance of the spinner i would suggest
To make your document fast to load you would want to make it as light as possible. You could go as far as removing everything but the body tag and load in content with scripts but that would be a big increase in complexity.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.