views:

65

answers:

2

Users in my site are seeing a half-second glitch on each page before any jQuery code executes. This code manipulates the page so you can visibly see elements move in one big chunk, making the user experience feel clunky. I'd prefer the page not to display at all until the JavaScript has run.

I'm using jQuery provided by the Google API in a page as follows:

<script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
<script type="text/javascript">
    google.load("jquery", "1.3.2");
</script>
<script type="text/javascript" src="MyScript.js"></script>

In MyScript.js:

google.setOnLoadCallback(runOnLoad);    
function runOnLoad() {
    // Do stuff
}

Does anyone know if it's possible to run the JavaScript before the page is displayed in the browser?

+3  A: 

You could probably add a css class to your main div that would hide the content, and then remove that class as the last thing that MyScript.js does.

In your html template:

<body>
    <div id="mainContent" class="hidden">
    </div>
</body>

The css class:

.hidden
{
    display: none;
}

Last executed statement of MyScript.js:

$("#mainContent").removeClass("hidden");
Jan Aagaard
A: 

I would agree with Jan.

Most (not all) browsers load CSS first before javascripts. So CSS would be advisable for you.

jerjer