Where Can You Place Javascript Tags?
Within a Web page, you can place JavaScript code in various locations. You can use script tags within the head and body sections, listing JavaScript functions and statements to execute. If you prefer to keep your JavaScript code in a separate file, you can link to the content of this file within the Web page head section. JavaScript excerpts also appear within HTML markup code, particularly in the form of event listener attributes.
-
Head Scripts
-
Web pages can include script areas for JavaScript code in the head section. The following sample markup demonstrates a JavaScript section you can list between the opening and closing head tags in your pages:
<script type="text/javascript">
/* JavaScript functions here */
</script>JavaScript code included in pages using this technique normally involves functions. These functions will only execute when some event causes them to -- for example, the page loading, or a user interacting with a Web page element.
Separate Scripts
-
You can include links to separate JavaScript files using amended script tags in Web page head sections. The following sample code demonstrates this practice:
<script type="text/javascript" src="myscriptcode.js"></script>
When this markup structure appears in a Web page, the user's Web browser will import the content of the script by requesting it from the location indicated as the source, or "src," attribute. The page can call functions in the imported script, using the same syntax it would for JavaScript functions listed directly in the head section.
-
Page Body
-
JavaScript code can appear within the page body section inside script tags. The following sample code demonstrates a script section with a simple code statement inside it:
<script type="text/javascript">
document.write("Hello");
</script>This technique allows developers to insert processing directly into a Web page. Unlike code listed within functions in the head section, JavaScript statements included this way in the page body area will execute when the page loads. This means that the code runs without having to be explicitly called on some event.
Event Attributes
-
JavaScript function calls often appear within the event listener attributes of HTML elements. In a typical scenario, a JavaScript resource, either in the page head section or a separate script with a link in the page head, will contain a list of functions, as in the following example:
function pressedMe(pressedID) {
alert("Pressed: " + pressedID);
}An HTML element can include code instructing the browser to call this function on user interaction, as follows:
<button type="button" id="button1" onclick="pressedMe(this.id)">Press Me</button>
When the user clicks this button, the Web browser will look for the function listed as the "onclick" listener attribute, calling it and passing the element ID attribute as a parameter.
-
References
Resources
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images