Web Platform

Javascript

Starting a script

First, create a new text file, and save it with a .js extension, such as "script.js".

Use the SCRIPT tag to reference the file in your HTML. Typically this is added at the very end of the BODY element:

<html>

  <head> ... </head>

  <body>

  ...

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

  </body>

</html>

It can be useful to put a bare minimum bit of code in your script file to make sure it gets loaded properly. You could add something like this in your Javascript file:

console.log('Hello');

Running a script

The most pain-free way of developing is to make it as quick as possible to see the results of your coding as you go along. Web technologies are perfect for this, because there is no need for manual - and usually slow - compilation steps. If you've followed the web setup steps, you can run a "live server" from the command line, or from within VS Code. A "live server" is a miniature web server that hosts your web code on your own machine. The primary benefit is that when you make a change to any files and save them, any web browser which is showing your content will automatically reload.

And check that "Hello" appears in your browser's console (available in its Developer Tools). With that established, you know your script gets loaded when it should.

Remote script references

You can also load in remote scripts. This is often used to load from a content distribution network, and save you the hassle of downloading and updating scripts. It's just a matter of using a different URL.

For example, this will load a particular version of d3, a powerful graphing library:

HTML:

<script src="https://d3js.org/d3.v5.min.js"></script>

Embedded Javascript

It is also possible, like CSS, to embed JS directly into your HTML. It is unadvisable for the same reasons we don't like to do it with CSS: it's hard to maintain. But if you want to, use the SCRIPT element, but put your Javascript source within the element:

HTML:

<script>

  console.log("Hello!");

</script>

Read more