How to use JavaScript

 How to make the browser execute JavaScript code? JavaScript code can be written in

<script>
...JavaScript Code...
</script>

The script tag (HTML tag) is executed by the browser. The <script>label can be placed anywhere on the page of HTML, such as <body>or <head>in.

Some examples on the Internet, will be used <script type="text/javascript" language="javascript">, but type="text/javascript"or language="javascript"are superfluous needed.

E.g

<!doctype html>
<html>

<head>
<script>
    alert('Hello world!');
</script>
</head>

<body>
My first JS page!
</body>
</html>

You can paste the above example into the HTML grid of JSFiddle , and then press Run to have a try.

Browser encounters <script>the label, it will stop parsing HTML file to execute first <scipt>inside the JS code wait until the complete implementation of the code, the next will continue to parse an HTML file.

Quoting JavaScript files

grammar:

<script src="JavaScript File address.js"></script>
JavaScript file extension file to .jsthe end

For example, if you write a JS code, the file name is hello.js, and the content is like:

alert('Hello world!');
Note that if the JavaScript code is written in a separate file inside, they do not add <script>tag Oh!

After you write it, for example, if you store it in the root directory of the website, you can quote this code in the web page like this:

<script src="/hello.js"></script>

You can also refer to external JavaScript files, such as referencing the jQuery library:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

It is a good habit and best practice to centrally write JavaScript code in .js files because:

  1. You can separate the JS code and HTML, so that they are not mixed and difficult to read and find.
  2. Different logic JavaScript codes can be written and stored separately for different files, which is convenient for maintenance and management.
  3. After the browser downloads the JS file, it will automatically cache a copy in the client computer, and there is no need to download it again afterwards, which speeds up the subsequent web page loading speed.

Practice writing JavaScript online

When you first started learning JavaScript, JSFiddle was a convenient online tool that allowed you to write, execute, and test JavaScript directly online. The method of use is very simple. You can write any code in the JAVASCRIPT block on the page, and then click Run on the upper left to execute it directly!

Post a Comment

0 Comments