简体   繁体   中英

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

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!

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.

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.

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM