Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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');
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!