Chapter 10. JavaScript in the DOM

10.1 Inserting and Executing JavaScript Overview

JavaScript can be inserted into an HTML document by including external JavaScript files or writing page-level inline JavaScript, which is basically the contents of an external JavaScript file literally embedded in the HTML page as a text node. Don’t confuse element inline JavaScript contained in attribute event handlers (i.e., <div onclick="alert('yo')"></div>) with page inline JavaScript (i.e., <script>alert('hi')</script>).

Both methods of inserting JavaScript into an HTML document require the use of a <script> element node. The <script> element can contain JavaScript code or can be used to link to external JavaScript files via the src attribute. Both methods are explored in the following code example.

Live code

<!DOCTYPE html>
<html lang="en">
<body>

<!-- external, cross domain JavaScript include -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.3.3/underscore-min.js"></script>

<!-- page inline JavaScript -->
<script>
console.log('hi');
</script>

</body>
</html>

Notes

It’s possible to insert and execute JavaScript in the DOM by placing the JavaScript in an element attribute event handler (i.e., <div onclick="alert('yo')"></div>) and using the javascript: protocol (e.g., <a href="javascript:alert('yo')"></a>), but this is no longer considered a modern practice.

Trying to include an external JavaScript file and writing page inline JavaScript using the same <script> element will result ...

Get DOM Enlightenment now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.