简体   繁体   English

Javascript:如何在加载javascript文件“async defer”后添加回调通知

[英]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 我使用async defer异步加载我的应用程序中的platform.js

<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. 我需要一个回调,它会通知我lib已成功加载或加载时出错。

Is it possible to add a callback in the Script tag? 是否可以在Script标签中添加回调?

Also, as there is a defer then there must be a promise , is't it? 而且,因为有一个defer那么必须有一个promise ,不是吗?

You can define an onload callback that will execute when the script has successfully loaded. 您可以定义在脚本成功加载时将执行的onload回调。 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. 请记住,如果您同步加载脚本,必须在上面的源代码中加载脚本之前定义onload回调函数。

Working example (asynchronous): 工作示例(异步):

https://jsbin.com/xavegojuzi/1/edit?html,console,output 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM