4

I am loading platform.js in my app asynchronously by using async defer

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer>
</script>

I need a callback that will notify me that the lib is loaded successfully or there is an error in loading.

Is it possible to add a callback in the Script tag?

Also, as there is a defer then there must be a promise, is't it?

1 Answer 1

3

You can define an onload callback that will execute when the script has successfully loaded. You can use this callback to maker sure your scripts run at the appropriate time in your application.

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer>
</script>

Please remember, in case you load the script synchronously, your onload callback function must be defined prior to loading the script above in your source code.

Working example (asynchronous):

https://jsbin.com/xavegojuzi/1/edit?html,console,output


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer></script>
<script>
  function onLoadCallback(){
    alert('your file has been loaded');
  }
  </script>   
  </head>
<body>    
</body>
</html>
Sign up to request clarification or add additional context in comments.

2 Comments

Many many thanks!! could you please clear some doubts please. 1. ?onload=onLoadCallback can work with any file loaded using async defer/sync? 2. what is the meaning of defer if there is no promise?
@VikasBansal defer, when present, it specifies that the script is executed when the page has finished parsing (no connection with a promise). Here a link to an useful article with more resources growingwiththeweb.com/2014/02/async-vs-defer-attributes.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.