HTML / javascript:在代码执行之前防止绘画 [英] HTML/javascript: prevent paint before code executes

查看:66
本文介绍了HTML / javascript:在代码执行之前防止绘画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面的末尾带有一个javascript文件。该文件放置在最后,以便我可以访问所有dom元素。
让我们说标记看起来像这样

I have a page with a javascript file at the end. the file is placed at the end so that I get access to all the dom elements. let us say the markup looks like this

<html>
<head></head>
<body>
//lot of markup here
<script src="my-js.js"></script>
<body>

示例标记只是为了显示我的js文件的位置。

the sample markup is just to show the location of my js file.

js文件(my-js.js)中的第一个类似

the first like in the js file (my-js.js) is

document.body.style.visibility = 'hidden';

代码运行后,我将可见性设置为隐藏

After the code runs I set the visibility back to hidden

据我了解(很多与此相关的文章,包括stackoverflow的文章)是浏览器到达js,然后执行它,然后继续进行渲染,然后绘制。
如果是这样,我所描述的代码应该可以正常工作。

From what I have understood(from a lot of articles related to this including in stackoverflow ones) is that the browser reaches the js, then executes it, and then continues with render and then paints. If that was true, my code as described should work fine.

但是,现在发生的是,该页面显示了(少于500ms ),就像执行代码之前一样,然后迅速隐藏起来,然后在执行代码之后再次显示。

However, what is happening now is that, the page is shown (for less than 500ms) as it is before the code executed, then quickly hidden and then shown again after the code executed.

简而言之,我想要的是:
页面是隐藏>代码执行>显示页面
相反,我得到的是
页面显示>页面隐藏>代码执行>显示页面

in short, what I want is: page is hidden > code executes > page is shown instead what I get is page is shown > page is hidden > code executes > page is shown

我的问题是为什么显示该瞬间的页面?

My question is why is the page shown for that split second? what am I doing wrong here?

PS:请注意,我无法更改js的位置,也无法添加其他位置。因此,请勿发布任何建议相同的解决方案。
更重要的是,我想知道为什么我的代码错误。

PS: Please note that I cannot change the location of the js nor add another. So, do not post any solution that suggest the same. More importantly, I want to know why my code is wrong.

推荐答案

您可能会对使用 defer 方法。

You might be interested in using the defer method.


defer表示等待解析器完成执行。大致相当于将脚本绑定到DOMContentLoaded事件,或使用jQuery.ready。当代码运行时,DOM中的所有内容将可供您使用。与异步不同,延迟的代码将按照在页面HTML中出现的顺序运行,只是延迟到完全解析HTML之后。

defer means "wait for the parser to finish to execute this". It’s roughly equivalent to binding your script to the DOMContentLoaded event, or using jQuery.ready. When the code does run, everything in the DOM will be available for you to use. Unlike async, defer’d code will run in the order it appears in the HTML of the page, it is just deferred until after the HTML is fully parsed.

例如:
< script src = my-js.js defer>< / script>

此处查看更多

这篇关于HTML / javascript:在代码执行之前防止绘画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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