Home > database >  Import JS function in HTML
Import JS function in HTML

Time:07-13

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 onl oad="initPage()">

But I get this error message:

Uncaught ReferenceError: initPage is not defined

I've found a Stackoverflow question but lost the URL to it. If someone knows which question I mean, please share the link and I'll delete this question

Thank you!

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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 onl oad="initPage()">
  </body>
</html>

and

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