Vikas Bansal Vikas Bansal - 3 months ago 7
Javascript Question

Javascript: How to add call back that notify after loading a javascript file "async defer"

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?

Answer

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>
Comments