amar ghodke
amar ghodke

Reputation: 471

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

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?

Upvotes: 0

Views: 830

Answers (1)

Reyno
Reyno

Reputation: 6525

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

Upvotes: 3

Related Questions