简体   繁体   中英

handle external javascript script loaded event before it's executed

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.

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! :)

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