Where to put JavaScript?
Where to put JavaScript
Just now we wrote the first JavaScript program, and we emphasized that JavaScript code must be placed in tags containing the code inside the
... tags. In fact, not only can this be done, we have two other ways to use JavaScript in HTML.JavaScript in head
In addition to placing the
tag, for example:JavaScript in head.
The execution result of this program is no different from the previous one, but in fact, the JavaScript code is placed in
There is a difference between ; and putting it in :Simply put, putting it in
will be better than putting it in is executed first. The code in the head tag will be parsed before the page starts drawing, while the code in the body will be executed when this code is read while the page is rendering.External JavaScript
In addition to writing JavaScript code directly in HTML, we can also write JavaScript code in a js file , call this js file in HTML. Let’s take “hello world” as an example.
In the laboratory environment, save the following code and name it "out.js" and put it on the desktop:
alert("hello word!");
Save the following code and name it "test2.html" and put it on the desktop:
my JavaScript code in "out.js"
Similarly, double-click the "test2.html" file on the desktop, call the browser to run, you will find that running The effect is no different from the previous two procedures.
In fact, the first two methods place the JavaScript code directly in HTML. When the page is loaded, the JavaScript code is parsed. If you place the JavaScript code in an external file, it will only be called and executed when the event is triggered and the JavaScript code is needed.
There is an advantage to this. When the page is relatively complex, putting a large amount of JavaScript code in an external file and only executing it when needed will significantly speed up the page loading speed.
In an HTML file, add different JavaScript codes at different locations, run and observe the order in which the JavaScript codes at different locations are executed.
Reference is as follows, observe the order of pop-up boxes: