简体   繁体   中英

Delay the firing of the 'onload' event

I have an API that a number of my clients use, using my own specifications and instructions for manipulating it from their own sites. It means that, unfortunately for me, changing the HTML code on their side is not an option. This is the general idea how their code looks and I need to make it still work after I do the changes I want:

<script src="player.js"></script>
<script>
    console.log(player.someProperty);
</script>

I want to do the following changes:

  • rename player.js to player_2.0.js
  • create a small script which will be named player.js so the HTML5 at the top would work like it did before. Then player.js would load player_2.0.js dynamically.

The problem is when the following part of the code gets to be exectuded

<script>
    console.log(player.someProperty);
</script>

player_2.0.js still isn't done loading, resulting player.someProperty to be undefined.

So my question is if I can manipulate or postpone the 'onload' event for player.js script until it's done loading player_2.0.js, or do anything that could get me accomplish that.

You're loading player_2.0.js asynchronously, therefore the code below is unable to access player.someProperty .

There is an old and ugly technique for synchronous loading, which uses Document.write()

In short:

<script type="text/javascript">
  document.write('<script type="text/javascript" src="other.js"></script>');
</script>

<script type="text/javascript">
  functionFromOther();
</script>

See document.createElement(“script”) synchronously for more details.

This is a very bad thing to do, since you will block the loading of other resources, and you can not inject this script dynamically without iframes.

I would rather use a technique called Friendly Iframes , but that will require some changes in your public API.

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