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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…