繁体   English   中英

如何制作一个总是先执行到最后执行的脚本?

[英]How can I make a script that always executes first to execute last?

我有两个脚本,由于异步编程,其中一个总是首先执行。

我需要使首先执行的脚本在另一个之后执行。

我正在使用 Google Apps 脚本编程

总是先执行的脚本

<script src="https://p.trellocdn.com/embed.min.js" defer></script>

我想先执行的脚本

  <script>
     google.script.run.withSuccessHandler(myname => {
     var elem = document.getElementById('myLink');
     elem.href = myname;
     }).getCardById();
  </script> 

Function getCardById()

function getCardById(){
  var app = SpreadsheetApp;
  var activeSp = app.getActiveSpreadsheet();
  var activeSheet = activeSp.getActiveSheet();
  var linkCol = activeSheet.getRange("B2").getValue();
  //Logger.log(' LINKCOL:' + linkCol);
  return linkCol;
}

问题

更改两个脚本执行异步任务的脚本加载顺序。

解决方案

做一些好的旧的(嗯,有点)动态内容加载怎么样? 考虑一下:您想在内容加载后立即调用后端getCardById() function,然后加载 Trello 库,然后对其进行处理。 因此,您需要:

  1. 使用getCardById()执行异步操作
  2. withSuccessHandler()中加载库
  3. 附加load侦听器以确保加载库
  4. load处理程序内进行准备工作
  5. 然后做其他事情

由于从您的代码判断,您的目标可能是嵌入带有从电子表格中提取的链接的 Trello 卡片,因此有一个帮助程序 function window.TrelloCards.load()可以根据需要重新查找卡片。

样本

<blockquote class="trello-card">
  <a id="card">Trello Card</a>
</blockquote>

<script>

  (() => {

    google.script.run.withSuccessHandler(() => {

      const tag = document.createElement('script');

      tag.src = "https://p.trellocdn.com/embed.min.js";

      tag.addEventListener('load', () => {

        //can start doing something cool...

        const elem = document.querySelector('#card');

        elem.href = 'your card url';

        window.TrelloCards.load(document); // <-- this triggers the lookup
      });

      document.body.append(tag);

    }).doSomethingServerSide();

  })();

参考

  1. 在 Atlassian 上按需嵌入

有问题。 以下是 defer 的含义: The defer attribute tells the browser that it should go on working with the page, and load the script “in background”, then run the script when it loads. Scripts with defer never block the page. Scripts with defer always execute when the DOM is ready, but before DOMContentLoaded event. The defer attribute tells the browser that it should go on working with the page, and load the script “in background”, then run the script when it loads. Scripts with defer never block the page. Scripts with defer always execute when the DOM is ready, but before DOMContentLoaded event.

所以这个脚本将在 DOM 加载之后但在 window.onload 事件发生之前运行。 下面的脚本要求 DOM 在运行之前已经加载,因此您需要将其放入 window.onload...

<script>
     google.script.run.withSuccessHandler(myname => {
     var elem = document.getElementById('myLink');
     elem.href = myname;
     }).getCardById();
</script> 

所以我认为你不会如愿以偿。 但有可能比我更了解 Javascript 的人可能会突然介入并挽救局面。

暂无
暂无

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

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