How do I Execute an External JavaScript When an HTML Web Page Loads?
Web sites use JavaScript to add function to basic HTML designs. With JavaScript, you can manipulate the visibility of elements, validate user-entered input, and change the cursor location, called the focus, on a page. You can call an external JavaScript function when a page loads by adding the location information to the "head" element of the page and use the "onload" action of the "body" element.
Instructions
-
-
1
Open the Web page that will call the JavaScript code in an appropriate editor program. A basic text-editor, such as Notepad or Wordpad, will work fine.
-
2
Locate the head tag in the HTML code. This should be near the top of the page, below the opening <html> tag.
-
-
3
Type the source page of the JavaScript code in a script block below the opening <head> tag. The script tag contains a type that indicates that it is a JavaScript element and a source that is the location of your JavaScript code. This can be an absolute or relative path.
<script type="text/javascript" src="myscript.js"></script>
-
4
Type the command to trigger the JavaScript function in the body onload element.
<body onload="myFunction();">
-
1
Tips & Warnings
JavaScript is a case-sensitive language. When typing the onload command, all letters should be in lower case. Your function name should exactly match the function definition on your external JavaScript.
JavaScript can be disabled in all popular browsers. Adding function using JavaScript is a welcome addition for users, but be sure that your page does not rely on it to function correctly.