Make Your Javascript External
By Submit Corner
Tell a Friend About This Page
Overview: Separate your Javascripts from your content and cut back on repeated
code that occurs on your webpages.
One of the often-overlooked bandwidth savers can be achieved by caching any
Javascripts and Cascading Style Sheets (CSS) that are repeated often on a
web site. For example, most web designers will repeat the same Javascript/CSS
code from page to page throughout a website. Designers can move commonly used
functions, code and style sheets into an external file and refer to the file with
one line from each page that requires it. This technique will enforce the external
file to be cached and will only be retrieved once until the cache is emptied or
expired.
HTML Code Before Making Javascripts External:
<HTML>
<HEAD><TITLE>Title Goes Here</TITLE></HEAD>
<script language="JavaScript">
function Sample() {...}
function Code() {...}
</script>
Continuation of HTML...
HTML Code After Making Javascripts External:
<HTML>
<HEAD><TITLE>Title Goes Here</TITLE></HEAD>
<script language="JavaScript" src="/functions.js"></script>
Continuation of HTML...
External Javascript Contents (functions.js):
Inside the external Javascript file, insert all functions, code and
Cascading Style Sheets which you wish to be used globally throughout
your website. Relating to the above example, you would insert the
code for all functions used, to look something like this:
function Sample() {...}
function Code() {...}
Search Engine Advantage
Another advantage of outsourcing Javascript code to external files is the
advantage provided for search engine indexing. Often, search engines that
read your pages will mis-interpret your Javascript code as content and will
index some of your code rather than useful content. Using this technique will
not reveal to search engines your Javascript code and possibly improve your
search engine rankings.