Julius Babies
Julius Babies

Reputation: 1861

Import JS function in HTML

I have a JS file that exports some functions. I need one of those in the download attribute of the HTML body tag. How do I import the JavaScript function into the inline HTML?

I tried the following:

JS file

export function initPage() { ... }

HTML file

<script type="module" src="js/script.js"></script>
<body onload="initPage()">

But I get this error message:

Uncaught ReferenceError: initPage is not defined

(This may be a duplicate Stack Overflow question, but I cannot find it again).

Upvotes: 0

Views: 1358

Answers (3)

Matteo Demicheli
Matteo Demicheli

Reputation: 184

You could try following:

{...}
<body>
{...}

<!-- End of the body -->
<script type="module">
import {initPage} from '...';

document.addEventListener('DOMContentLoaded', function(event) {
  initPage();
});
</script>
</body>

Basically the event listener DOMContentLoaded might be a modern way of solving your problem.

Upvotes: 2

Joacim Norbeck
Joacim Norbeck

Reputation: 1

I did some tries and what seemed to work for me was to remove type="module" from the script tag and the export from the js function

Edit: What I meant was something like this

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="/js/script.js"></script>
  </head>
  <body onload="initPage()">
  </body>
</html>

and

function initPage() {
  console.log('hupp');
}

Upvotes: 0

Julius Babies
Julius Babies

Reputation: 1861

I've found a solution which is very easy, not quite exact that what I wanted but it works:

<script type="module">
    import {initPage} from "./js/file.js";
    document.querySelector("body").onload = function () { initPage(); } ;
</script>

Now the <script>-Tags with a src attribute aren't necessary anymore.

Upvotes: 0

Related Questions