Javascript Tricks, Samples, Tutorials & Howtos

New versions notifications available via

Follow jtricksdotcom on Twitter
/ JTricks.com / Placing javascripts inline (together with page markup) or in separate files
Last updated: 01 May 2012
Placing javascripts inline (together with page markup) or in separate files
There are two distinct ways to add javascripts to your page. You can put javascripts inside your HTML markup (inline) or into separate files on your web server.

The inline method, on the other hand doesn't require additional files to be placed on the web server and the browser doesn't make separate request(s) for the javascript source body, allowing it to execute immediately.
Inline javascript placement
To place inline javascript into page add the following to your HTML:
<script type="text/javascript"><!--
 ...your javascript code here...
//--></script>
The HTML comment tags <!-- and //--> are to prevent ancient browsers that don't understand scripts from displaying the script code. The normal behaviour of the browsers that don't understand a tag is to render its contents as if the tag wasn't there. All modern browsers running on computers will understand this tag, however some obscure handheld devices or phones might not.

Putting javascript sources into separate files requires the browsers to make separate requests to web server to get the scripts. Therefore this method might increase the page load time unless the script code is already in the cache. Modern browsers and techniques of HTTP/1.1 (such as Keepalive and HTTP pipelining) have increased the performance of putting scripts into separate files.
Referencing external javascripts
To reference javascript file in page add the following to your HTML:
<script type="text/javascript" src="specify script file URL here">
</script>
Normally you want to place your script in separate file if at least some of your users will visit more than one page with the same script.
Converting inline placement to referencing external javascripts
The javascript samples on this site are shown using the inline method. However, they can be converted to separate files in the following way:

  • Put the script to a separate file on your web server (preferable with extension .js, if you want to remember where your javascripts are).
  • Remove the following lines from the file:
<script type="text/javascript"><!--
//--></script>
  • Put the following line into your page HTML, specifying the script file URL:
<script type="text/javascript" src="specify script file URL here">
</script>