The purpose of creating JavaScript was to construct a scripting language that works in a web browser. Web pages are HTML documents. Whereas JavaScript is a programming language, whose code can be embedded in HTML documents and which can process these documents.
Over the years, this part of JavaScript has not been fully standardized and each browser provider could implemented it in its own way. With time, similarities have become the standard. Now JavaScript in web browser is standardized by W3C as part of HTML standard.
In contrast to programming languages that are executed on the server side, JavaScript in web browser is executed exactly in a web browser. Therefore, this part of JavaScript is called client-side JavaScript.
Browser environment
Browser is the fundamental host environment for the JavaScript. It is a platform that extends the core JavaScript and provides additional features through specific objects and functions.
The core object for JavaScript in web browser is the window object. It represents web browser window and simultaneously the ECMAScript Global object. The window object has properties that specify details of the browser window (navigator, location, history) and methods (alert(), setTimeot()) which perform various operations.
However, the most important property of the window object is document. The document object represents content in the window. Its properties and methods allow you to read, traverse and modify content of Web documents.
Another important part of JavaScript in web browser is handling events. Event handler allow you to define function, that is called when specified event (for example an click) occurs.
Besides, there are numerous APIs that provide useful services and they allow you to create real Web applications. The most important of them is XMLHttpRequest object which enables communication with servers.
Embedding JavaScript in HTML
There are several possibilities for embedding JavaScript into HTML. Each of them is described below.
Inline scripts
You can embed the JavaScript code inline in HTML document between the <script> and </script>tags. It can be placed both in the <head> section and anywhere in the body section.
<!DOCTYPE html> <html> <head> <title>Inline JavaScript</title> <script> function getDay() { var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var dayNo = new Date().getDay(); return days[dayNo]; } </script> </head> <body> <div>Always the current day</div> <script> var message = 'Today is: ' + getDay(); alert(message); </script> </body> </html>
In the past it was the most common way of embedding of JavaScript in HTML.
Scripts in external files
JavaScript code can be stored in an external JavaScript file. To include the external JavaScript file into HTML use the <script> tag with the specified src attribute. As a value of the src attribute set a url of the JavaScript file.
<script src="js/javascriptfile.js"></script>
By convention JavaScript files have a .js extension. It is not obligatory but it is recommended to use this extension.
If a <script> tag has specified the src attribute any content between the opening and closing <script> tag is ignored. Whereas the content of an external file is treated as if it was directly contained between the <script> and </script> tags. A JavaScript file should contain pure JavaScript code without any HTML tags.
An external JavaScript file you can include both in the <head> section and in the body section of a HTML document.
javascriptfile1.js:
function getMonth() { var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var monthNo = new Date().getMonth(); return months[monthNo]; }
javascriptfile2.js:
function displayMonthInfo() { var message = 'Month is: ' + getMonth(); alert(message); } displayMonthInfo();
HTML document:
<!DOCTYPE html> <html> <head> <title>JavaScript in external file</title> <script src="/js/javascriptfile1.js"></script> </head> <body> <div>Always the current month</div> <script src="/js/javascriptfile2.js"></script> </body> </html>
The use of external files allows you to separate the JavaScript code from the HTML code. As a consequence HTML documents are smaller in size and the overall code structure is more readable.
When more than one page uses the same JavaScript code, placing it in an external file means you only use one copy of the code and avoid duplicating it.
A code from an external file needs to be downloaded only one time, on the first page which uses this code. Next pages retrieve this code from browser cache. This affects the speed of page loading.
External JavaScript files can come not only from the same domain as the Web page but also from any external server. It allows you to use JavaScript libraries directly from external resources, such as well-known CDNs.
Scripts in an event handler attribute
You can register an event handler by assigning a function to a specific property of an Element object representing HTML element. These properties are for example onclick, onchange and onload.
JavaScript event handler properties have their equivalents in HTML attributes with the same name. This allows you to define event handler by placing the code in HTML attributes. Specify the code as the value of an event handler attribute in the HTML element.
<div onclick="var date = new Date(); alert(date);"> Show current time </div>
The value of an event handler attribute forms the body of a function and this function is assigned to related event handler property. Such a defined event handler attribute may contain any number of statements, separated by semicolon. Usually however it includes simple code like a function call.
This technique was popular in the past. Currently it is recommended to keep HTML and JavaScript separately to ensure a more clean code.
Scripts in URLs
To include JavaScript in a URL use the javascript: protocol followed by a JavaScript code. It is interpreted as a single line of code. If there are multiple statements, they should be separated by semicolons. The javascript: can be used in any place which expect URL, especially in hyperlinks.
<a href="javascript:alert('JavaScript Tutorial');">What is this?</a>
If the executed code returns a value not equal to undefined, browsers use this value to display as a new content of web page. Browsers behave differently here, eg Firefox always replaces current value by returned one, Chrome and IE only if the value is a string or not equal to zero number. To avoid overwriting the document content, use the void operator, to force return of undefined.
<script> function myAlert(text) { alert(text); return text; } </script> <a href="javascript:void myAlert('JavaScript Tutorial');">What is this?</a>
Nowadays, this type of JavaScript embedding is rarely used and is not recommended.
Execution of JavaScript Programs
JavaScript program can be considered as entire JavaScript code that is embedded in a web page. The program consists of all parts of inline code, all included external files both from own domain and other domains, code embedded as event handlers and with the javascript: protocol. All these parts of code share one global scope and the global window object.
Script loading phase and event driven phase
In the phase of loading the contents of the document JavaScript code is executed from top to bottom. JavaScript is run in the order in which it is defined in the document. This applies to both inline and external scripts. This phase is relatively short and lasts up to several seconds.
In the next phase when the script has already been loaded, JavaScript is run asynchronously and event-driven. This phase lasts as long as the web page is displayed. Periods of inactivity are interwoven with events and their handling. In response to occuring events web browser calls event handler functions. Events may be triggered by the browser itself. For example the load event appears when the document is fully loaded. It is one of the first events and often it is used in programs to initialise application or run some functions only when all elements of the document are available for reading and manipulation. Other triggers of events may be user interactions (clicks, mouse scrolling), HTTP communication, timers or errors.
Synchronous execution
Synchronous execution is a default way of processing JavaScript code when web page is loaded. It means that when HTML parser meets a <script> tag it stops rendering the document and processes JavaScript. If the script refers to an external JavaScript file, the file is downloaded and then the code is executed. Only after this rendering is resumed. Synchronous execution due to the way it works is also called blocking script execution.
Note that the <script> elements are often placed in the <head> section of the document. This usually helps to keep the code clean. However it blocks rendering of the web page until JavaScript files are downloaded and code is interpreted.
Another approach is to place the <script> elements embedding external files just before the closing
Reply