title: how to dynamically add script tags at the end of the body element
body: <p>I want to remove render blocking javascript. So, i am trying to dynamically add <code>script</code> tags at the end of the <code>body</code> element after page has loaded.</p>
  
  <p>I have 7 <code>script</code> tags that i want to add dynamically. One of the <code>script</code> tag loads <code>jQuery</code> using a CDN. Remaining 6 <code>script</code> tags load javascript that depends on <code>jQuery</code>.</p>
  
  <p>I have put all the links to javascript files in an array and then using a loop, i am creating a <code>script</code> element, adding required attributes on it and appending it to the <code>body</code> element.</p>
  
  <p><strong>Problem:</strong>  </p>
  
  <p>Problem is that when i view the page in the browser, i get errors in the console regarding <code>jQuery</code> not being defined.</p>
  
  <p>I am adding the <code>script</code> tags in the correct order and i have verified that <code>script</code> tags are indeed added at the end of the <code>body</code> element and are added in the correct order.</p>
  
  <p>This problem occurs everytime on initial load and if i refresh the page then sometimes scripts are loaded correctly and sometimes i get the same error that <code>jQuery</code> is undefined.</p>
  
  <p>As a result of this problem, some of the animations on the webpage are not triggered and also i am using <code>slick</code> carousel. When javascript is not loaded correctly, all the images, that should be displayed in <code>slick</code> carousel, are displayed one after the other.</p>
  
  <p><strong>Question:</strong> </p>
  
  <p>Why is <code>jQuery</code> undefined when other scripts, that are dependant on <code>jQuery</code>, execute? What is the correct way to dynamically add <code>script</code> tags in the <code>html</code>?</p>
  
  <p><strong>Code:</strong></p>
  
  <p>This is how i am adding <code>script</code> tags in the <code>html</code>. All scripts are loaded from local filesystem except <code>jQuery</code> and <code>slick carousel</code> which are loaded via a CDN.</p>
  
  <pre><code>&lt;script&gt;
    function loadJs() {
      const arr = [
        "https://code.jquery.com/jquery-3.3.1.min.js",
        "//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js",
        "./js/jquery.waypoints.min.js",
        "./js/jquery.counterup.min.js",
        "./js/wow.min.js",
        "./js/lazysizes.min.js",
        "./js/loso.js",
      ];
  
      for (let srcLink of arr) {
          let script = document.createElement("script");
  
          script.setAttribute("type", "text/javascript");
          script.setAttribute("src", srcLink);
  
          document.body.appendChild(script);
      }
    }
  
    window.addEventListener("load", () =&gt; {
      loadJs();
    });
  &lt;/script&gt;
  </code></pre>