script element. A
Inline HTML comment markersEdit
The inline HTML comments are to prevent older browsers that do not understand the
script element from displaying the script code in plain text.
Older browsers that do not understand the
script element will interpret the entire content of the
script element above as one single HTML comment, beginning with "<!--" and ending with "-->", effectively ignoring the script completely. If the HTML comment was not there, the entire script would be displayed in plain text to the user by these browsers.
Current browsers that know about the
script element will ignore the first line of a
The use of comment markers is rarely required nowadays, as the browsers that do not recognise the
In XHTML, the method is somewhat different:
Linking to external scriptsEdit
src="script.js" to the opening
src would be "js/script.js".
Location of script elementsEdit
The script element may appear almost anywhere within the HTML file.
A standard location is within the
head element. Placement within the
body however is allowed.
<!DOCTYPE html> <html> <head> <title>Web page title</title> <script></script> </head> <body> <!-- HTML code here --> </body> </html>
There are however some best practices for speeding up your web site  suggested by the Yahoo! Developer Network that specify a different placement for script tags: to put scripts at the bottom, just before the </body> tag. This speeds up downloading, and also allows for direct manipulation of the DOM while the page is loading. It is also a good practice to separate HTML documents from CSS code for easier management.
<!DOCTYPE html> <html> <head> <title>Web page title</title> </head> <body> <!-- HTML code here --> <script src="script.js"></script> </body> </html>
Controlling external script evaluation and parser blockingEdit
As an alternative to placing scripts at the bottom of the document body, loading and execution of external scripts may be controlled using async or defer attributes. Asynchronous external scripts are loaded and executed in parallel with document parsing. The script will be executed as soon as it is available.
<!DOCTYPE html> <html> <head> <title>Web page title</title> <script async src="script.js"></script> </head> <body> <!-- HTML code here --> </body> </html>
Deferred external scripts are loaded in parallel with document parsing, but script execution is deferred until after the document is fully parsed.
<!DOCTYPE html> <html> <head> <title>Web page title</title> <script defer src="script.js"></script> </head> <body> <!-- HTML code here --> </body> </html>