Load src javascript from file on click

65 Views Asked by At

I am trying to load a .js file into a div that is located in a folder on my desktop when I click a link. I will have 100's of js files. I do have the

<script type="text/javascript" src="Apple.js"></script>

in there, but there will be 100's of these where the page will start to load slow if I have all of these in there in the html file. Is there a way I can have the page load quickly, then when I click on the link go out and retrieve the individual js file? When the page loads I will have another js file that will be retrieving all of the links. Can I somehow put this

<script type="text/javascript" src="Apple.js"></script>

in the

<a onclick="GetApple();"/>Apple</a>

so when clicked it knows what file and where to retrieve it?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>TITLE HERE</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <meta name="viewport">
</head>
<body>
  <div id="LinksList"> 
    <a onclick="GetApple();"/>Apple</a>
  </div>
  <div id="ScriptList"> 
  </div>
</body>

<script type="text/javascript" src="GetLinks.js"></script>  ```
<script type="text/javascript" src="Apple.js"></script>

<script>
  window.onload = function() {
    GetLinksList()
  }
</script>
1

There are 1 best solutions below

0
IT goldman On

You may want to add a <script> tag to page having the src as the url of the file. Please note that this is asynchronous action. Here's an example with a nice wrapper.

// from https://stackoverflow.com/a/69616316/3807365
function addScript(src) {
  return new Promise((resolve, reject) => {
    const s = document.createElement('script');

    s.setAttribute('src', src);
    s.addEventListener('load', resolve);
    s.addEventListener('error', reject);

    document.body.appendChild(s);
  });
}


document.querySelector(".my-button").addEventListener('click', async function(ev) {
  await addScript(ev.target.getAttribute("data-src"))
  console.log("jquery loaded!", $)
  $(ev.target).css("background", "red")

})
click to <button class="my-button" data-src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js">load jquery</button>