As soo n as we become aware of the environment in which our programs run, it be-
comes of paramount importance to know where to put the code and how the code
is executed. So far we put our examples into <sc ript> e le ments embe dded within
HTML code, which is convenient for learn ing and quick testing, but discouraged in
modern web design. Recall that HTML, CSS, and JavaScript each play their own
individual role inside a web page by separately defining content, presentation, and
behavior. Also recall how you separate CSS code from HT ML by putting it to a sep-
arate file and linking both by mean s of the <link> HTML element. You can separate
JavaScript from HTML in the same way and put it in an external file, which you
connect with HTML using the src attribute of th e <script> element. JavaScript de-
tached this way is also called unobtrusive JavaScript, and for an obvious reason —it
makes HTML code much mor e readable because there are no blocks of JavaScript
code sitting in between the sections of HTML code. This is not the so le advantage
of such a separation, though. For example, if multiple HTML files share the same
JavaScript code, you can maintain only a single copy of the code , rather than having
to edit each o f the HTML files whenever you want to change it.
Mike: If y ou put JavaScript code into an external file and include it by mea ns of a
<script> element, then I suppose that everything else stays the same. I mean the
position of the <script> e le ment doesn’t change, does it?
Professor: If you want to implement the con cept properly, then <s cript> elements
shouldn’t be scattered all over HTML code either. This is a proble m so long as you use
document.write() to write to the browser window. Namely, even if JavaScript code
is placed to an external file, it is still executed synchronously. Th is means that it is
executed exactly when the <script> element referring to it is encountered during the
document parsing. The parser will wait until the code has executed before proceeding
with the parsing of the HTML that follows. If you use any doc ument.write() m eth-
ods, the text produced by those methods will be inser te d into the current location in the
input stream of H TML code that is being parsed. So you cannot m ove JavaScript code
that c ontains any calls to document.write( ) without also changing the lo cation of
the output they pro duce.
Another p roblem with document.write() is that you canno t use it after the docu-
ment parsing process ha s completed. Calling it after the document has closed will
erase the document completely. As soon as you want to design a page that is respon-
sive to user actions, this is not the kind of behavior that you would want. That’s why
document.write() is ra rely, if at all, used in modern web pages.
Maria: I suppose that you will show us alternatives.
Professor: Indeed I will, we’re coming to tha t shortly. But first things first: I need to
tell you about events so we can start executing JavaScript code asynchronously.
12.3 Events
Professor: When the docu ment loads completely and the web page is displayed, the
story is usually not finished. On the contrary, it’s on ly now that interesting things begin
to happen. After the document has been parsed and lo aded, the JavaScript enters its
230 Meeting 12. Using JavaScript to Control the Browser
asynchronous mode, which mean s that it is executed as needed in response to user and
other events. An event is any action that a com puter program detects an d handles. For
example, an event may be triggered when a visitor clicks a mouse button o r presses a
key, or when a timer expires.
It is fairly easy for the programmer to han dle an event because all objects that could
detect and react to events have predefine d event-handler properties attach ed to them
for every possible event. All you have to do as a programm er is to define an event-
handler function and a ssign it to the corresponding property. The event-handler func-
tion is then invoked automatically by the p rogram whenever a corresponding event
occurs. Event-handler p roperties can be easily rec ognized because they have names
that begin with “on. For example, if you want to do something whenever the ob je ct
named cl ickMe is clicked, then you should write code like this:
clickMe.onclick = function() { /* Do something awesome */ };
Maria: What’s that clickMe o bject?
Professor: It is an imaginary object that could represent any HTML elem ent on the
page that your visitor can click. You’ll soon learn how to c apture actual HTML el-
ements from inside JavaScript in order to manipulate them. What I wanted to show
you right now is how to c onnect a f unction definition with the onclick event-handler
property of an arbitrary object that can actually be clicked. Once you have written
the above code, something awesome will be done each time someone clicks the e le -
ment represented by the clickMe object. Because you don’t know in advance when
and how many times, if at all, c lickMe will be clicked, you also d on’t know when,
if at all, something awesome will be done. That’s why we say that JavaScript events
are handled asynchro nously, in contrast to the timely, synchronous execution of code
during the web-p age parsing.
Because JavaScript actually invokes a function as a response to an event, you can also
think of the JavaScript event-handling mechanism as simply calling the ap propriate
function every time an event occurs. For example, if you click three times on the
HTML element represented by the clickMe object, the method onclick() is invoked
three time s as shown on this picture.
time
Event
Response
click
click
click
clickMe.onclick()
clickMe.onclick()
clickMe.onclick()
It’s ab out time to look at a concrete example of handling an event. One of the most
important event-handler properties is the onload handler of the Window object. It
is triggered immediately after the document parsing and loading is complete and the
document is visible within the browser window. You will frequently write JavaScript
12.3. Events 23 1
code right inside the onload handler.
Imagine that you have the fo llowing simple HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>External JavaScript</title>
<script src="/scripts/tools.js"></script>
</head>
<body>
<p>I’m plain HTML.</p>
</body>
</html>
Notice that there’s no JavaScript in this code but the document includes an external
JavaScript file named
tools.js. External JavaScript code is referenced using the src
attribute of the <scri pt> HTML elem ent, whose value represents the URL of the
desired file. Notice also that because <scr ipt> is not a void element it needs the
closing tag even though it has no content.
Inside th e
tools.js file there is the following code:
window.onload = function() {
alert("I handle the load event.");
};
Note that an external JavaScript file should contain only pure JavaScript code with-
out any <scri pt> tags, just like an external CSS file only contains CSS code. By
convention, the name extension of a JavaScript file is
.js.
As you can see, ther es really not much to the above JavaScript code. The function
definition, which only calls the global a lert() function, is assigned to the onload
event handler. Right after the HTML document has loaded completely, a load event
fires and the function attached to the on load handler is invoked. This opens the dialog
displaying the message “I handle the onload event. If you reload th e document, you’ll
get the message again, of course. Be careful to put the
tools.js file into the right fo lder
so that the src attribute of the <script> element finds it.
Maria: And that’s inside the
scripts sub-f older o f our roo t folder, rig ht?
Professor: Pre cisely.
Maria: Why did you use the win dow identifier? You said that it is not needed, and
that its properties can be used a s though they were global variables, didn’t you?
Professor: That’s true. The above example would by all means work just as well
without explicitly referring to window. It is, however, the usu al convention to use
window with the onload handler to make it more obvious that the handler is for the
Window and not some other object.
232 Meeting 12. Using JavaScript to Control the Browser
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.249.90