How to include javascript in your webpage
One method is to include the JavaScript statements directly into the HTML file, just like we did in the previous section:
<script> ... Javascript statements are written here ... </script>
A second, and usually preferable way to include your code is to save your JavaScript into a separate file, and use the <script> element to include that file by name using the src (source) attribute:
<script src='mycode.js'></script>
The preceding example includes the file mycode.js, which contains our JavaScript statements. If your JavaScript file is not in the same folder as the calling script, you can
also add a (relative or absolute) path to it:
<script src='/path/to/mycode.js'></script>or
<script src='http://www.example.com/path/to/mycode.js'></script>
Placing your JavaScript code in a separate file offers some important advantages:
- When the JavaScript code is updated, the updates are immediately available to any page using that same JavaScript file. This is particularly important in the context of JavaScript libraries, which we look at later in the tutorial.
- The code for the HTML page is kept cleaner, and therefore easier to read and maintain.
- Performance is slightly improved because your browser caches the included file; therefore, having a local copy in memory next time it is needed by this or another page.
try yourselft....
<!DOCTYPE html> <html> <head> <title>A Simple Page</title> </head> <body> <p>Some content ...</p> <script src='mycode.js'></script> </body> </html>
When JavaScript code is added into the body of the document, the code statements are interpreted and executed as they are encountered while the page is being rendered. After the code has been read and executed, page rendering continues until the page is complete.