Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
596 views
in Technique[技术] by (71.8m points)

jquery - Load javascript before rendering page?

I want to run some jquery code before my page have loaded. Im adding some classes which are changing the css with javascript, and when the page loads i see the "old" css for a short time. Any ideas? Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I want to run some jquery code before my page have loaded.

This is easily done; it's funny because much of the time, people are trying to do it the other way around.

When the browser encounters a script tag, barring your using a couple of special attributes (and the browser supporting them), all processing of the page comes to a screeching halt and the browser hands the script to the JavaScript engine. Only when the script completes does processing of the page continue.

So if you have a script tag in the head section of your page, you can output CSS classes via the document.write function:

<DOCTYPE html>
<html>
<head><title>Foo</title>
<script src='jquery.js'></script>
<script>
if (some_condition) {
    document.write("<style>foo { color: blue; }</style>");
}
else {
    document.write("<style>foo { color: red; }</style>");
}
</script>

Note that some_condition in the above can only rely on, and refer to, the items above it in the document (since the browser hasn't done anything with the rest of the document yet, as it's waiting to see what document.write content the script is going to output).

Live example (refresh it a few times, half the time it's red, half the time it's blue). It doesn't use jQuery, but you get the idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...