Guru
Guru

Reputation: 1

Blocking all UI using pure JavaScript

How to block all UI things in a webpage until all JavaScript files including jquery.js are loaded completely. Is there any possibility to do it using only JavaScript?

Upvotes: 0

Views: 1820

Answers (5)

dfsq
dfsq

Reputation: 193261

Add some kind of this snippet at the very top of you body:

<div class="loading-overlay" id="loading">
    <div class="loading">Loading..</div>
</div>

and this styles inline in HEAD:

<style>.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, .6);
    z-index: 1000;
}
.loading {
    font-size: 20px;
    text-align: center;
    color: #FFF;
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
}</style>

Then after all javascript files execute this code:

document.getElementById('loading').style.display = 'none';

Make sure z-index property of the overlay is high enough to cover everything on the page.

However this solution is not reliable if some of your heavy scripts are loaded asynchronously.

Example: http://jsfiddle.net/ucPLW/

Upvotes: 2

You can use the $(window).load() event for your code since this happens after the page is fully loaded and all the code in the various $(document).ready() handlers have finished running.

$(window).load(function(){
  //your code here
});

Upvotes: 0

Alec Moore
Alec Moore

Reputation: 1175

If by "UI Things," you mean the DOM, then you can put your javascript either at the end of your html like so:

<html>
    <head>...</head>
<body>

<script>
     // This javascript will execute after the HTML has loaded
</script>
</body>
</html>

Or if you want to use JQuery then you can put your UI code in a document ready function like this:

 $(document).ready(function() {
      // This javascript will also execute after the HTML has loaded
 });

Best of Luck.

Upvotes: 0

Madhur
Madhur

Reputation: 2219

You can add a css mask with z-index set to higher than all your other ui elements on the page

In your page

<body>
<div class="mask"></div>
..
..
</body>

CSS

.mask {
   position: fixed;
   top: 0px;
   width: 100%;
   height: 100%;
   padding: 0px;
   margin: 0px;
   background: #666;
   overflow: hidden;
   opacity: 0.7;
   z-index: 99;
}

Once your jQuery is loaded, hide this mask.

$( document ).ready(function() {
    $('.mask').hide();
});

Upvotes: 2

King Friday
King Friday

Reputation: 26076

Statically listing the script tags in the head will ensure they are loaded before the DOM. This has been the case for as long as I can remember.

<html>
    <head>
        <!-- insert your script tags here -->
    </head>
    <body>
       <!-- your DOM here -->
    </body>
</html>

Its recommended to load the scripts at the bottom of the page instead so I'm not sure your motivations for this.

Upvotes: 1

Related Questions