如何在打印前等待javascript文件加载twitter,并在打印后关闭选项卡

How to wait for javascript file to load twitter before printing and close the tab after printing

本文关键字:打印 选项 加载 等待 javascript 文件 twitter      更新时间:2023-09-26

嘿,我正在使用推特嵌入的延迟加载来加载到我的页面上。目前我已经给出了2000的setTimeout,之后我使用window.print()打印页面。但是,如果网络连接很慢,那就不起作用,如果网络速度好,那就是浪费时间。此外,打印后,我需要关闭我使用window.close() 的选项卡

block main-script
  // build:js /js/lazy-x.js
  script(src="/js/lazy-x.js")
  // endbuild
  script.
    document.addEventListener("DOMContentLoaded", myFunction);
    function myFunction() {
      setTimeout(function(){
        var file_name = ("{{article['title']}}".replace(/[^0-9a-zA-Z_?: .]/g, ""));
        document.title="Scroll - "+file_name;
        window.print();}, 2000);
        window.onfocus=function(){ window.close();}
    }

这是我正在处理的jade文件。我需要等待lazy-x.js加载每个twitter嵌入,然后会出现打印对话框,打印后我需要关闭选项卡。但选项卡没有关闭。

我不确定你的问题是否正确。您可以在脚本上执行onLoad:

function importScript (sSrc, fOnload) {
    var oScript = document.createElement("script");
    oScript.type = "text'/javascript";
    oScript.onerror = loadError;
    if (fOnload) { oScript.onload = fOnload; }
    document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
    oScript.src = sSrc;
}

示例来自:https://developer.mozilla.org/en/docs/Web/API/HTMLScriptElement

那么你的代码是:

importScript('/js/lazy-x.js', function() {
    var file_name = ("{{article['title']}}".replace(/[^0-9a-zA-Z_?: .]/g, ""));
    document.title="Scroll - "+file_name;
    window.print()
});

也可以在玉石模板中进行

script(type="text/javascript" src="path_to_js" onload ="callMyFunction()")

另一件事,在window.focus上,你想关闭窗口,它可能会阻止打印/停止JS。代替window.focus检查window.onafterprintwindow.onbeforeprint事件