javascript101之代码运行

来源:互联网 发布:金十数据直播室 编辑:程序博客网 时间:2024/06/05 22:56

外部代码

  第一个推荐建议是在外部文件(以.js为扩展名)中编写代码,然后在我们的网页中使用一个HTML <SCRIPT>标签的src属性指向文件的位置。如果你想在其他地方使用它,使javascript独立在一个文件中可以减少代码的重复。这样可使浏览器能够在远端的客户计算机上缓存该文件,减少页面加载时间。

<!-- Code is written in a .js file, then included via the script tag src attribute. --><script src="/path/to/example.js"></script>

内联代码

第二个可选是在网页中直接内联代码。这里也是使用HTML <SCRIPT>标签来实现,代码的src属性指向到一个文件而不是放在标签之间虽然也有使用该选择的例子,但大部分情况下都是在一个单独的文件中保存代码,如上所述。

<!-- Embed code directly on a web page using script tags. --><script>alert( "Hello World!" );</script>

属性

最后一个选择是使用HTML元素的事件处理器。这个方法最好不要使用。

<!-- Inline code directly on HTML elements being clicked. --><a href="javascript:alert('Hello World');">Click Me!</a><button onClick="alert('Good Bye World');">Click Me Too!</a>

代码放置

前面的两个选项的代码放置重要的,可以根据不同的情况有所不同如果你的javascript代码不访问页面上的元素可以安全地放置脚本在关闭HTML中的标签<head>之前。相反,如果你需要访问网页的元素,那你要确保在你的javascript代码执行之时,你所访问的元素在页面上存在。下面的例子中可以看出,这种常见的陷阱将被执行找到元素ID“hello-world”的脚本,在文档元素定义之前将执行

<!-- Attempting to access an element too early will have unexpected results. --><!doctype html><html><head><script>var title = document.getElementById( "hello-world" );console.log( title );</script></head><body><h1 id="hello-world">Hello World</h1></body></html>

一种常见模式移动脚本页面的底部,在HTML标签<body>关闭之前。这样可以确保在代码执行之时元素已经定义。

<!-- Moving the script to the bottom of the page will --><!-- make sure the element exists. --><!doctype html><html><head></head><body><h1 id="hello-world">Hello World</h1><script>var title = document.getElementById( "hello-world" );console.log( title );</script></body></html>


原创粉丝点击