JavaScript/JavaScript within HTML: Difference between revisions

[checked revision][checked revision]
Content deleted Content added
→Linking to external scripts: - This has been deprecated per HTML5
Line 73:
 
== Linking to external scripts ==
JavaScript is commonly stored in a file so that it may be used by many web pages on your site. This makes it much easier for updates to occur and saves space on your server. This method is considered a best practice. This is because it separates a page's behavior (JavaScript) from its content (HTML), and it makes it easier to update code. If several pages all link to the same JavaScript file, you only have to change the code in one place.
 
Add <ttcode>src="<var>script.js</var>"</ttcode> to the opening <ttcode>script</ttcode> tag. ReplaceThis <var>means that the JavaScript code for this page will be located in a file called "script.js</var>" withthat is in the pathsame todirectory as the web page.js If the JavaScript file containingis located somewhere else, you must change the <code>src</code> attribute to that path. For example, if your JavaScript file is located in a directory called "js", your <code>src</code> would be "src/script.js".
 
Because the server provides the content type when the file is requested, specifying the type is optional when linking to external scripts. It's still advised to specify the type as <tt>text/javascript</tt>, in case the server isn't set up correctly, and to prevent HTML validation complaints.
 
<source lang=HTML4strict>
<script type="text/javascript" src="script.js"></script>
</source>
 
== Location of script elements ==