[thelist] JavaScript - linking v. embedding

Andrew Clover and-evolt at doxdesk.com
Thu Jun 10 15:42:58 CDT 2004

David Siedband <david at calteg.org> wrote:

> Are there guidelines for when javascript should be linked as a separate 
> file and when it should be embedded?

Linking is usually best. You then don't have to worry about a number of 
HTML escaping issues that can otherwise be confusing.

Embedding, however, may be more convenient where:

   - the scripting involved is very short
   - the code is not shared over multiple pages
   - the page is generated by the server (through PHP etc.) and you want
     to include dynamic JavaScript (eg. setting up an array of data for
     another linked script to handle).

Inline script (onclick etc.) has further escaping issues and is often 
better replaced with direct listener assignment from JS.

> Are there variations in how browsers treat these two options?

Normally, no: the browser must execute the scripting, whether embedded 
or linked, before continuing with the parsing of the rest of the document.

This is not necessarily the case if you use <script defer> (or 
defer="defer" in XHTML), which can allow the browser to take its time 
over loading scripts; in this case a linked script may run a bit later 
than an embedded one if the browser has to fetch it. <script defer> is 
not globally supported though, and rarely used ATM.

Andrew Clover
mailto:and at doxdesk.com

More information about the thelist mailing list