DEV Community

Charlie @ 90-10.dev
Charlie @ 90-10.dev

Posted on • Originally published at 90-10.dev on

Getting Started with Javascript

JavaScript in HTML

Here are a couple of different way to run JavaScript directly in your browser.

HTML header

<html>
  <head>
    <title>Webpage</title>
    <script type="text/javascript">
      console.log("here");
    </script>
  </head>
  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

HTML body

<html>
  <head>
    <title>Webpage</title>
  </head>
  <body>
    <script type="text/javascript">
      console.log("here");
    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

External File

Given a file named app.js, to include it in an HTML file named index.html:

<html>
  <head>
    <title>Webpage</title>
    <script src="app.js"></script>
  </head>
  <body></body>
</html>

Enter fullscreen mode Exit fullscreen mode

ES6 - import & export

In the example below, we'll use 2 JavaScript files:

export function House() { 
  this.width = 100;
  this.length = 200;
}
Enter fullscreen mode Exit fullscreen mode

my-script.js

function paint() { 
  ...
}
function clean() { 
  ...
}
export { paint, clean }
Enter fullscreen mode Exit fullscreen mode

second-script.js

To include them both in an HTML file:

<html>
  <head>
    <title>Webpage</title>
    <script type="module">
      import { House } from "./my-script.js";
      import { paint, clean } from "./second-script.js";
      let house = new House();
    </script>
  </head>
  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

ES10 - dynamic import with async Early days Google Chrome only

export const helloEvent = () => {
  console.log('Hello World');
};
Enter fullscreen mode Exit fullscreen mode

my-script.js

<html>
  <head>
    <title>Webpage</title>
    <script type="text/javascript">
      window.onload = function() {
        document.getElementById('helloButton').addEventListener("click", async() => {
          const module = await import('./myscript.js');
          module.helloEvent();
        });
      }
    </script>
  </head>
  <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

index.html

Top comments (0)