你什么时候把Javascript放在体内,当你在头上和使用doc.load时? [英] When do you put Javascript in body, when in head and when use doc.load?

查看:204
本文介绍了你什么时候把Javascript放在体内,当你在头上和使用doc.load时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将Javascript放在HTML文件中的位置?

我应该在正文或html的头部写脚本吗?

我一直在想,主要是因为在创建页面时我总是遇到麻烦,基于以下内容:

I've always wondered, mainly because when creating pages I always run into trouble, based on the following thing:

你什么时候写javascript

When do you write your javascript


  • <在< < body>用 $(文件).ready()

  • In the <head>
  • In the <body>
  • with a $(document).ready()

我可能是傻瓜,但是由于错误的地方或是或否的 doc.ready()命令,我有几次没有执行我的JavaScript(/ jQuery)。所以我真的很想知道。

I could be stupid, but I've had a few times when my JavaScript (/jQuery) wasn't executed because of the wrong place or yes or no doc.ready() command. So I'm really wondering so.

同样适用于jQuery和'var'命令

Same goes for jQuery and 'var' command

推荐答案

$(document).ready()只需确保在加载javascript之前加载所有DOM元素。

$(document).ready() simply ensures that all DOM elements are loaded before your javascript is loaded.

无关紧要

无需等待此活动开始,您最终可能会操纵页面上尚未存在的DOM元素或样式。 DOM ready事件还允许您更灵活地在页面的不同部分上运行脚本。例如:

Without waiting for this event to fire, you may end up manipulating DOM elements or styles that are yet to exist on the page. the DOM ready event also allows you more flexibility to run scripts on different parts of the page. For example:

<div id="map"></div>
<script type="text/javascript">document.getElementById('map').style.opacity = 0;</script>

将运行,因为在脚本运行之前已加载了map div。事实上,您可以将脚本置于底部,从而获得一些相当不错的性能改进。页面。

will run because the map div has been loaded before the script runs. In fact, you can get some pretty good performance improvements by placing your scripts at the bottom of the page.

什么时候重要

但是,如果你正在加载你的脚本在< head> 元素中,你的大多数DOM都没有加载。此示例不起作用:

However, if you are loading your scripts in the <head> element, most of your DOM has not loaded. This example will not work:

<script type="text/javascript">document.getElementById('map').style.opacity = 0;</script>
<div id="map"></div>

不会,因为地图div尚未加载。

will not, since the map div has not been loaded.

一个安全的解决方案

你可以通过等到整个已加载DOM:

You can avoid this by simply wait until the entire DOM has loaded:

<script type="text/javascript">$(document).ready(function () { 
    document.getElementById('map').style.opacity = 0;
});
</script>
<div id="map"></div>

有很多文章解释了这一点,以及 jQuery文档本身。

There are plenty of articles that explain this, as well as the jQuery documentation itself.

这篇关于你什么时候把Javascript放在体内,当你在头上和使用doc.load时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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