what is the right way to append all Js files using Jquery append

白昼怎懂夜的黑 提交于 2021-01-29 07:34:13

问题


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

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>

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>

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

My question are

  1. Is this really better approach to load all script like this and must be followed all the times?
  2. If yes What I need to optimize above code so that it will load entire scripts and append to html?

回答1:


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

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


来源:https://stackoverflow.com/questions/63724492/what-is-the-right-way-to-append-all-js-files-using-jquery-append

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!