How to Execute an External Java Script When an HTML Web Page Loads
How fast a Web page loads often depends on much more than the Internet connection speed of the computer accessing a page. Whenever a site visitor requests a page on your website, the Web server must parse all the code in the page before some scripts or events execute. If your site uses complex JavaScript to perform certain functions, it might be faster to call an external script when the page loads rather than include many lines of code on the displayed page. Using external scripts also allows you to avoid duplicating code on multiple pages that use a single script.
Instructions
-
Create the External JavaScript
-
1
Launch an HTML or text-editing application on your computer. Click "File" > "New" on the menu bar to create a new file.
-
2
Create a new JavaScript, or copy and paste code from a repository website or another source. An example of simple JavaScript:
Function.pop() {
Alert("This is a test script")
}
When called, the above script opens a pop-up message box with the text "This is a test script."
-
-
3
Click "File" > "Save." Save the new script with a descriptive file name with a ".js" file extension. For the example script, the name of the file is "test.js".
Call the External Script from a Web Page
-
4
Launch the HTML or text editor on your PC. Open the Web page file in which you want to execute the external JavaScript.
-
5
Locate the "<head>" tag in the HTML code. Position the mouse cursor at the end of the tag and press "Enter" to create a page break in the code.
-
6
Enter code to call and execute the external JavaScript. To call the example script, enter the following code:
</script src="test.js">
</script>
-
7
Save the modified file in the HTML or text editor. Save the modified HTML file in the same folder or directory as the external JavaScript file.
-
8
Launch a Web browser application. Open the modified HTML to execute the external script. If using the example script, opening the Web page causes the "This is a test script" message box to appear on the screen.
-
1
Tips & Warnings
When uploading the modified HTML file and JavaScript file to your Web server, be sure to save both files in the same directory or folder.