18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5<br />

❑<br />

❑<br />

Code Maintenance — If <strong>JavaScript</strong> code is sprinkled throughout various pages, code maintenance<br />

becomes a nightmare. It is much easier to have a directory for all <strong>JavaScript</strong> files so that when a<br />

<strong>JavaScript</strong> error occurs, there is no question about where the code is located.<br />

Caching — Browsers cache all externally linked <strong>JavaScript</strong> files according to specific settings,<br />

meaning that if two pages are using the same file, it is only downloaded once. This ultimately<br />

means faster loading times. Including the same code in multiple pages is not only wasteful, but<br />

also increases the page size and thus increases the download time.<br />

Tag placement<br />

Generally speaking, it is common to place all code and function definitions in the tag of an<br />

HTML page so that the code is fully loaded and ready for use once the body is rendered. The only code<br />

that should appear within the tag is code that calls the functions defined previously.<br />

When the tag is placed inside of the tag, the script is executed as soon as that part<br />

of the page is downloaded to the browser. This makes it possible to execute <strong>JavaScript</strong> code before the<br />

entire page is loaded. <strong>For</strong> example:<br />

<br />

<br />

Title of Page<br />

<br />

function sayHi() {<br />

alert(“Hi”);<br />

}<br />

<br />

<br />

<br />

<br />

sayHi();<br />

<br />

This is the first text the user will see.<br />

<br />

<br />

In this code, the sayHi() method is called before any text is displayed on the page, meaning that the<br />

alert pops up before the text “This is the first text the user will see.” is ever rendered. This method of<br />

calling <strong>JavaScript</strong> inside the of a page is not recommended and should be avoided whenever<br />

possible. Instead, it is recommended to use <strong>JavaScript</strong> only as an event handler in the body of a page,<br />

such as:<br />

<br />

<br />

Title of Page<br />

<br />

function sayHi() {<br />

alert(“Hi”);<br />

}<br />

<br />

<br />

<br />

128

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!