在渲染页面之前加载javascript? [英] Load javascript before rendering page?

查看:1620
本文介绍了在渲染页面之前加载javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的页面加载之前运行一些jquery代码。我添加了一些使用javascript更改css的类,当页面加载时,我会在短时间内看到旧css。有任何想法吗?谢谢

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

推荐答案


我想在我的页面加载之前运行一些jquery代码。

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.

当浏览器遇到脚本时标签,除非您使用一些特殊属性(以及支持它们的浏览器),所有页面处理都会暂停,浏览器会将脚本交给JavaScript引擎。只有在脚本完成后才会继续处理页面。

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.

因此,如果您在<中有脚本标记code> head 页面部分,您可以通过 document.write 函数输出CSS类:

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>

注意上面的 some_condition 只能依赖并参考文档中它上面的项目(因为浏览器还没有对文档的其余部分做任何事情,因为它正在等待查看 document.write 脚本将输出的内容)。

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).

实例(刷新几次,一半是红色,一半是蓝色)。它不使用jQuery,但你明白了。

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.

这篇关于在渲染页面之前加载javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆