Question

If I have a page which gets generated using PHP and then modified using JS which runs using:

window.onload=myFunction;

Then the user sees the original page, which then appears to flick around as the js code gets run and adds its own bits onto the page.

Is there a way to avoid the user being able to see this process, or to at least make it less obvious to them? Maybe there is a more suitable method of loading the javascript than window.onload (one that can begin to work as the images etc. are downloading)?

Was it helpful?

Solution

I would recommend first settings some class on the body which will toggle the visibility of some elements.

<body class="loading"> .... </body>

Then, when the script finishes loading, you can remove this class and show all the things you need. You can even use the "loading" class to show some fancy background, like a spinning circle of dots in Mozilla.

Also some projects use another method of loading scripts instead of "onLoad". First you create a global array, let's say, named "domReady".

window.domReady = [];

And when you need to add some function that will be run on page load, you just push it into this array:

window.domReady.push( function foo(){ alert('Hey!'); } );

And at the last line of the document you put the function that will run all the pushed procedures:

for (procedure in window.domReady) {
    window.domReady[procedure].call();
}

Since it will be the last line of the document before the closing tag, the DOM will be ready, and you won't have to wait until all the images are loaded.

OTHER TIPS

OK I found this little nugget of jquery which works a treat:

$(document).ready(function() {
  //Call your function here
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top