【问题标题】:Add defer to existing script with jquery使用 jquery 将延迟添加到现有脚本
【发布时间】:2021-09-10 04:50:32
【问题描述】:

我想在标题上添加延迟到特定的 Javascript 标记。

我无法手动添加它,因为 javascript 是显示 onload 并且我无法控制它。

那么我可以使用任何 jquery 添加延迟到 javascript 吗?

感谢您的帮助

【问题讨论】:

  • 你的问题不是很清楚。您能否举一个当前代码的示例,以及您希望它产生什么结果?
  • @CertainPerformance 我基本上有一个
  • @CertainPerformance 我在哪里添加 derfer?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: javascript html jquery optimization script


【解决方案1】:

如果您可以在其他脚本运行之前运行 JavaScript 代码,您可以使用 MutationObserver 拦截并删除它,直到 DOM 加载完毕,防止它中断加载和阻塞。例如:

<script>
  // YOUR SCRIPT
  new MutationObserver((_, observer) => {
    const script = document.querySelector('script[src*="jquery"]');
    if (!script) return;
    observer.disconnect();
    script.remove();
    window.addEventListener('DOMContentLoaded', () => {
      console.log('DOMContentLoaded, loading jQuery now...');
      document.body.appendChild(script);
      script.addEventListener('load', () => {
        console.log('jQuery loaded now:', typeof jQuery);
      });
    });
  })
    .observe(document.body, { childList: true });
</script>
<!-- Uncontrollable page script: -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  // Example script to show that jQuery is not loaded by this point:
  console.log('Example script sees:', typeof jQuery);
</script>

【讨论】:

    猜你喜欢
    • 2023-04-05
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    相关资源
    最近更新 更多