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

149
Views
Running a js function in html while the script tag has a defer attribute set

I the defer attribute of the script tag in the <head> section of HTML files. This almost always means that I cannot run js functions in the HTML since the js file is only loaded after the HTML file has been loaded..

I have run into a situation where I needed to run a js function in my HTML file, but would not want to remove the defer attribute from the script tag because of other functions in the js file. I looked at the possibility of using async, but it also was not helpful.

Any idea on how this could be done... other than using defer? I would still like to keep the script tag in the head, but going that way would mean that I have no open (non-function based) instructions in the linked js file... which is not always ideal.

Here is a sample of the HTML file

temp.html

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="temp.js" defer></script>
    <title>Defer et al</title>
</head>

<body>
    <script>
        runThisFunction('Home');
    </script>
</body>

</html>

And here is a sample of the js file

temp.js

function runThisFunction(varin) {
    console.log(varin);
}

If I remove the defer from the js file, the function will run; if I leave it there, or use async instead, the function will not run because it has not loaded yet.

Any assistance in this small issue will be appreciated.

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

0

The best way to do this would be to refactor your script to contain an entry point in a function, and run that function once the DOM loads. Instead of, for example

// temp.js

function runThisFunction(varin) {
    console.log(varin);
}

document.querySelector('.foo').textContent = 'doing stuff';
// other code here

put all of the functionality that depends on the page being loaded into its own function:

// temp.js

function runThisFunction(varin) {
    console.log(varin);
}

function init() {
  document.querySelector('.foo').textContent = 'doing stuff';
  // other code here
}
window.addEventListener('DOMContentLoaded', init);

This way, if you also remove the defer attribute, runThisFunction will be available immediately, but the other parts of your code won't run until the page is loaded.

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!