【问题标题】:what is the right way to append all Js files using Jquery append使用 Jquery append 追加所有 Js 文件的正确方法是什么
【发布时间】:2020-12-22 17:48:37
【问题描述】:

我正在尝试使用此视频@3:30 Optimize your code: load code at the right time 中解释的方法加载所有 js 文件

我在 index.js 中实现了这种方法

<script>
 var scripts  = '<script src="./js/jquery-3.5.1.min.js"/>'+
  '<script src="./js/jquery-ui.min.js"/>'+
  '<script src="./js/bootstrap.min.js"/>'+
  '<script src="./js/index.js"/>';
    $(window).on("load",function(){
$("body").append(scripts)
});
</script>

也尝试过在 html 头标签中

 <script>
 var scripts  = '<script src="./js/jquery-3.5.1.min.js"/>'+
  '<script src="./js/jquery-ui.min.js"/>'+
  '<script src="./js/bootstrap.min.js"/>'+
  '<script src="./js/index.js"/>';
    $(window).on("load",function(){
$("body").append(scripts)
});
</script>

它仍然没有加载我在脚本标签中传递的所有 js 文件,也没有加载到网络选项卡中。

我的问题是

  1. 这样加载所有脚本并且必须始终遵循这种方法真的更好吗?
  2. 如果是,我需要优化以上代码,以便加载整个脚本并附加到 html?

【问题讨论】:

  • 如果你还没有加载jquery,你不能使用$(window).on("load"
  • 通过append()添加的脚本标签也不会被执行。你必须使用$.getScript,附加一个实际的脚本dom元素对象,或者使用本机api
  • 那么我必须在脚本标签中加载 jquery 和其他文件吗?那么只加载单个外部本地文件没有任何好处。
  • 不,只是 jquery - 如果您使用 CDN,那么您的浏览器很有可能已经对其进行了缓存处理 - 因此从 CDN 加载将比从本地延迟加载
  • @freedomn-m : 我的项目中不允许使用 CDN,我必须使用 Jquery、Jquery-UI、Bootstrap4.js 和 index.js。我必须在 head 中添加所有脚本文件,然后将 index.js 添加为 append ?

标签: javascript jquery performance optimization render-blocking


【解决方案1】:

jQuery 还没有加载,所以你不能使用它。所以我建议你使用香草 javascript 解决方案。 (在结束正文标记&lt;/body&gt;之前添加为内联脚本标记)

const scripts = [
  "./js/jquery-3.5.1.min.js",
  "./js/jquery-ui.min.js",
  "./js/bootstrap.min.js",
  "./js/index.js",
];

window.addEventListener("DOMContentLoaded", () => {
  for(const script of scripts) {
    const scriptTag = document.createElement("script");
    scriptTag.src = script;
    document.body.appendChild(scriptTag);
  }
});

编辑:如果您需要以特定顺序加载脚本。您可以使用“加载”事件来启动下一个。见下面的sn-p

const scripts = [
  "./js/jquery-3.5.1.min.js",
  "./js/jquery-ui.min.js",
  "./js/bootstrap.min.js",
  "./js/index.js",
];

window.addEventListener("DOMContentLoaded", () => loadScript(scripts, 0));

function loadScript(scripts, index) {
  if (!scripts[index]) return;

  const scriptTag = document.createElement("script");
  scriptTag.src = scripts[index];
  scriptTag.addEventListener("load", () => loadScript(scripts, index + 1));
  document.body.appendChild(scriptTag);
}

【讨论】:

  • 我必须在 html 中添加 然后它才会加载所有脚本对吗?
  • 不——你不要把这个脚本放在index.js中——你直接把它放在页面中,或者用&lt;script src标签分开从您包含的文件
  • @amarghodke 不,您应该在结束
猜你喜欢
  • 2011-12-31
  • 2015-08-03
  • 2021-07-24
  • 2018-01-05
  • 1970-01-01
  • 2014-10-09
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多