1
votes

I have an html page and a script which I want to handle in specific way: after it's loaded but before it's executed. Basically I want to pre-load script but execute when certain criteria met. Script doesn't depend on other scripts so I make it non-blocking (async):

<script onload='onScripLoad()' scr='...' async></script>

All I want is something similar to onload but which is executed before the downloaded script. Is it possible?

The issue here is that I'm able to pre-load the script but unable to sync with the required event in my app lifecycle. The onScripLoad is executed after script has been loaded AND after it has been executed. What I need is to have control when script is executed (postpone execution).

Adding more details I want to pre-load the script and execute it when certain element is available in the body but I cannot put the script right after that element because in this case it gets queued with a few other resources which are being downloaded in the head. Thus I want to place my script in the head, make it async and once it's downloaded execute only when specific element is available (or event create that element before executing). I cannot make it not async because it's a script which I have no control and wouldn't like my whole page depend on it.

1
Can't you put the code in the external script in a function and then only call that function once both conditions are true?nnnnnn
Can't you just house the logic in the external script in a function, which gets loaded early, and then call that function from a secondary script when a certain condition is true?Obsidian Age
That is how I would do it if I have control over the external script. Unfortunately it's a 3d party library and it has certain javascript which is executed right after begin downloaded.Alexey Strakh

1 Answers

2
votes

You could just load the external script in the head section, wrap the logic inside a function, and then call that function inside a condition at a later point:

externalscript.js:

function externalFunction(data) {
  console.log(data);
}

Index:

<head>
  <script src='externalscript.js' async></script>
</head>
<body>
  <script>
  var body_data = 'test';
  if (timing-driven-condition) {
    externalFunction(body_data);
  }
  </script>
</body>

The function externalFunction would be loaded first, but wouldn't be used until it was called within the condition, giving you control over when it executes.

Hope this helps! :)