使用 Jquery append 附加所有 Js 文件的正确方法是什么 [英] what is the right way to append all Js files using Jquery append

查看:58
本文介绍了使用 Jquery append 附加所有 Js 文件的正确方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此视频 @3:30 中解释的方法加载所有 js 文件 优化您的代码:在正确的时间加载代码

I am attempting to load all js files using approach explained in this video @3:30 Optimize your code: load code at the right time

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

I have implemented this approach in index.js as

<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 head 标签中一样尝试

also tried as in html head tag

 <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 文件,也没有加载到网络选项卡中.

still it does not loads all js files which I am passing in script tags and not loading in network tab as well.

我的问题是

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

推荐答案

jQuery 尚未加载,因此您无法使用它.所以我建议你使用 vanilla javascript 解决方案.(在结束正文标签</body>之前添加为内联脚本标签)

jQuery isn't loaded yet so you can't use it. So i suggest you use a vanilla javascript solution. (Add as inline script tag right before the closing body tag </body>)

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);
  }
});

如果您需要以特定顺序加载脚本.您可以使用加载"事件开始下一个.见下面的片段

If you need the scripts to load in a particular order. You can use the "load" event to start the next one. See snippet below

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);
}

这篇关于使用 Jquery append 附加所有 Js 文件的正确方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆