Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...