JavaScript Introduction to External Files


JavaScript can be placed in the <body> and the <head> sections of an HTML page. In HTML, JavaScript code must be inserted between <script> and </script> tags.

Older examples may use a type attribute: <script type=”text/javascript”>. The type attribute is not required. JavaScript is the default scripting language in HTML.

A JavaScript function is a block of JavaScript code, that can be executed when “called” or “asked” for. For example, a function can be executed when an event occurs, like when the user clicks a button.

You can place any number of scripts in an HTML document. Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both. It is a good idea to place scripts at the bottom of the <body> element. This can improve page load, because script compilation can slow down the display.

External JavaScript

Scripts can also be placed in external files. External scripts are practical when the same code is used in many different web pages. JavaScript files have the file extension .js. To use an external script, put the name of the script file in the src (source) attribute of the <script> tag. You can place an external script reference in <head> or <body%gt; as you like. The script will behave as if it was located exactly where the <script> tag is located.

<!DOCTYPE html>
<html>
<body>
<h1>External JavaScript</h1>
<p id="demo">A Paragraph.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> myFunction is stored in an external file called "myScript.js".</p>
<script src="myScript.js"></script>
</body>
</html>

Placing JavaScripts in external files has some advantages. It separates HTML and code thereby making HTML and JavaScript easier to read and maintain. Cached JavaScript files can speed up page loads.

JavaScript Output

JavaScript does NOT have any built-in print or display functions. It can however “display” in a few different ways.

Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Writing into the browser console, using console.log().

<script>
// A JavaScript one-line comment
// a popup window with an OK button.
window.alert(5 + 6);
</script>

<script>
// just displays 11 on the screen.
document.write(5 + 6);
</script>


// Using document.write() after an HTML document is fully loaded, 
// will delete all existing HTML! 
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button onclick="document.write(5 + 6)">Try it</button>
</body>


<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>


// In your browser, you can use the console.log() method to display data.
// Activate the browser console with F12, and select "Console" in the menu.
<script>
console.log(5 + 6);
</script>

Leave a comment

Your email address will not be published. Required fields are marked *