Fuego DeBassi
Fuego DeBassi

Reputation: 3017

Explicitly setting load order

I have a slight problem.

I need to show some safety information in a JS drawer that the page loads with open. The images creating the drawer are kind of hefty and as such the safety text in the drawer render prior to the background, creating a really ugly loading experiance. Is there a easy way I can say

DO NOT LOAD safetyText UNTIL safetyBG is loaded ?

We're not using any libraries (i.e. jQuery) so a JS solution would have to work as a script by itself.

Upvotes: 0

Views: 161

Answers (1)

Korneel Bouman
Korneel Bouman

Reputation: 201

If I understand you correctly, you only want to display safetyText once safetyBG has fully loaded. To achieve that, hide safetyText, then check on document.onload if safetyBG has loaded. If so, show text, if not, attach function to show text to safetyBG.onload:

function showSafetyText() {
  //show text
}

window.onload = function() {

  var safetyBG = document.getElementById("safetyBG"); // tweak as necessary

  //have to check to see if img loaded, if you would simply assign showSafetyText
  //to img.onload, it would never run if the img was fully loaded already

  if (!safetyBG.complete) {
     safetyBG.onload = showSafetyText;
  } else {
     showSafetyText(); 
  } 

}

You mentioned images (rather than a single image) in your post. If that's the case you'll want to write a function that loops through the images to check to see if they've all loaded (at which time you can load the text); then attach this function to each of the images' onload events (unless all images are loaded already in which case you can simply show the text).

Upvotes: 1

Related Questions