1

I tried the code snippet given by Google for the use of the spreadsheet API in JavaScript from here. It works but I don't understand the following part.

<script async defer src="https://apis.google.com/js/api.js"
    onload="this.onload=function(){};handleClientLoad()"
    onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

In particular, why the code is written that way instead of as follows:

<script async defer src="https://apis.google.com/js/api.js"
    onload="handleClientLoad()">
</script>
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Alberto
  • 163
  • 4
  • 3
    I'm frankly amazed it uses `onload` at all. It's not 1998 anymore, no one should be using `on...` handlers anymore. – Mike 'Pomax' Kamermans Apr 22 '19 at 20:23
  • 2
    @Mike'Pomax'Kamermans: It's likely the most concise cross-browser/version snippet. If you wanted to use the DOM API to add the event handlers you would have to add some way to find the element (e.g. ID) and make sure that that doesn't collide with other elements. This is pretty much self contained and will "just work". – Felix Kling Apr 22 '19 at 20:24
  • that seems unlikely, though, `(function blah(...) { ... })();` works in any browser with even the most basic JS support, and doesn't require any kind of `onload` monitoring of the script. It simply runs when parsing is complete. (you might very well be right, of course, but then someone at Google didn't realise onload was unnecessary) – Mike 'Pomax' Kamermans Apr 22 '19 at 20:25
  • @Mike'Pomax'Kamermans: *"It simply runs when parsing is complete."* Uh? The `onload` handler runs when the code the script element is referring to was evaluated. That happens some time in the future. – Felix Kling Apr 22 '19 at 20:31
  • @Mike'Pomax'Kamermans Regardless of your preferences, inline JavaScript is still extremely common. Programming teachers and tutorials don't adopt modern techniques quickly, they keep teaching the same way they have for decades. – Barmar Apr 22 '19 at 20:34
  • Assigning to `this.onload` inside the `onload=` attribute seems very weird. When the inline code finishes running, would it still execute a new `onload` handler? – Barmar Apr 22 '19 at 20:37
  • 1
    I think this might be a workaround for IE < 10 not understanding `async`. There's some mention of that [here](https://www.html5rocks.com/en/tutorials/speed/script-loading/) – Barmar Apr 22 '19 at 20:40

1 Answers1

1

According to this question from a few years ago, not all browsers support the load event on script tags (guess which one…). That's why they are listening on the readystatechange event as well, and when the script was loaded they call the onload handler. The handler overwrites itself with an empty function so that handleClientLoad() is not called twice.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375