Adding client-side JavaScript

In the third chapter, we started work with Node.js, which was JavaScript that ran on the server side. Now, we're going to introduce client-side JavaScript, or JavaScript that runs on the browser.

To run JavaScript on the browser, you will need to add a script tag anywhere in the HTML document.

The standard script tag looks like this:

    <script>
console.log('Executing client side javascript ...')
</script>

It is better, however, to put your JavaScript code in a separate file altogether, which is when you would use the alternate syntax:

    <script src="script.js"></script>

Add this script tag as the last element inside <body>.
Along with this, include a file called script.js in the public directory and populate its contents with this:

    console.log('Executing client side javascript...')

Open your browser and open its console (commonly opened by right-clicking anywhere and going to the Inspect element. Here's how it looks when run on Firefox:

Even though you can add JavaScript anywhere in the document, it is recommended that you have it as the last element in your HTML body. This is because the document is rendered synchronously, and any JavaScript present is executed before the rest of the document is loaded. Putting the JavaScript in the end ensures that your users do not see the document getting stuck half way.
..................Content has been hidden....................

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