'Preload and defer JS and call functions therein within the HTML doc

Suppose there's a JS file:

// a.js
function a(){ console.log('hello from a.js') }

and an HTML file where I want to preload and defer the a.js JS file such that I can call functions in a.js from within b.html:

<!-- b.html -->
<html>
<head>
  <link re='preload' as='script' href='a.js'>
</head>

<body>
</body>

<script defer src='a.js'>  <!-- calling a() below doesn't work -->
<script       src='a.js'>  <!-- calling a() below does    work -->

<script>
a()  // doesn't work with `defer`, works without `defer`
</script>
</html

How can I accomplish that?

One way is to wait for the page to load:

<script defer src='a.js'>
<script>
window.addEventListener('load', function(){ a() })  // Works
</script>

but this is rather inelegant. Is there a better way?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source