当前位置:网站首页>JS resource disaster recovery

JS resource disaster recovery

2022-06-21 09:14:00 Tie Hanhan plus

JS Resource disaster tolerance

In order to speed up the first loading of the project , Sometimes we use some online plug-ins to introduce ( for example cdn Introducing plug-ins ), But online plug-ins will inevitably have some inevitable problems , For example, the plug-in server crashed 、 The plug-in will not be updated for a long time , All these will cause the online plug-ins introduced by the project to fail to work properly , This may cause the project to fail to work properly . therefore ,js Disaster recovery of resources is still very necessary .

Ideas

stay script Add a onerror Method , When online resources fail to load , stay onerror Method to manually add static js resources

Concrete realization

Let's introduce clipboard plug-in unit To test

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <!--js Methods that fail to load need to be defined in advance -->
  <script> function jsLoadErr (e, s) {
      console.log(e, s) alert('js Loading failed ') var new_s = document.createElement('script'); new_s.setAttribute('type', 'text/javascript'); new_s.setAttribute('src', s); var head = document.getElementsByTagName('head')[0]; head.appendChild(new_s); //  Remove the failed online load script e.remove(); } </script>
  <!-- Will be online src Deliberately change the address of the failed access to test -->
  <!-- Right online src Address :https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js-->
  <!--cdn load js When you fail ,onerror Method will automatically load static resources -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2/clipboard.min.js" onerror="jsLoadErr(this, 'static/pulugins/clipboard/clipboard.min.js')"> </script>
</head>
<body>
  <h1 class="test">js disaster </h1>
  <script> window.onload = function () {
      var clipboard = new ClipboardJS('.test') console.log(' clipboard ', clipboard) } </script>
</body>
</html>


原网站

版权声明
本文为[Tie Hanhan plus]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221446082099.html