How to load javascript files using event listeners

Yuseff

This question is not duplicate of

Conditionally load JavaScript file

and nor this

How to include an external javascript file conditionally?

I have gone through them, they are kind of similar to what I want to do but not exactly same. Here is how, in the above question the user just wants to load the script file once based on a condition. But in my case I want to load different js files based on click events.

So here in my case I have an HTML document:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Experiment</title>
    <link href="s.css" rel="stylesheet" type="text/css">
    
</head>
<body>
    <div class="navigation">
        <nav>
            <ul>
                <li id="home_btn"> Home</li>
                <li id="about_btn"> About </li>
            </ul>
        </nav>
    </div>

    <canvas id="myCanvas">

    </canvas>

    <div class="notePane">
        <p> This is just a bunch of text not explanation</p>
    </div>
   
</body>
<script src="./exp.js" type="text/javascript"></script>
</html>

and this h.html file is linked to an exp.js file. Now in the exp.js file :

var h_btn = document.getElementById("home_btn");
var a_btn = document.getElementById("about_btn");
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type="module";


h_btn.addEventListener("click", showHome );
a_btn.addEventListener("click", showAbout);

function showHome() {
   
    js.src="./j1.js";
    head.appendChild(js);
}

function showAbout() {
    js.src="./j2.js";
    head.appendChild(js);
}

So things work fine when I click the h_btn on the web page. It loads j1.js. But then when I click on the a_btn on the web page I expect to see j2.js linked but I don't see it. I have to refresh the page and then click on a_btn to see j2.js linked. How do I link j1.js and j2.js such that I don't have to refresh the page again and again to load the correct script.

Terry

This is because of how Node.appendChild() works. The first click works because you're creating a new element and inserting it into your document. However, the second click will not work as you've expected because the node already exists:

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node. If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position

This means that the second click will only mutate the src attribute of the already-injected <script> element instead of creating a new one, and that also means that the second script src will not be loaded.

A solution will be to use a function that will create a script tag every single time:

var h_btn = document.getElementById("home_btn");
var a_btn = document.getElementById("about_btn");
var head = document.getElementsByTagName("head")[0];
h_btn.addEventListener("click", showHome);
a_btn.addEventListener("click", showAbout);

function insertScript(src) {
  var js = document.createElement("script");
  js.type = "module";
  js.src = src;
  head.appendChild(js);
}

function showHome() {
  insertScript('./j1.js');
}

function showAbout() {
  insertScript('./j2.js');
}

But this will also mean that multiple clicks on the same button will cause the script to be injected multiple times. This does not affect browser performance much since the browser has the loaded script cached somewhere, but to guard against this, it might be a good idea to implement some kind of unique identifier per script, and check against that before injection. There are many ways to do this, and this is just one way:

var h_btn = document.getElementById("home_btn");
var a_btn = document.getElementById("about_btn");
var head = document.getElementsByTagName("head")[0];
h_btn.addEventListener("click", showHome);
a_btn.addEventListener("click", showAbout);

// Store scripts that you've injected
var scripts = [];

function insertScript(src) {
  // If we have previously attempted injection, then do nothing
  if (scripts.indexOf(src) !== -1) {
    return;
  }
  
    var js = document.createElement("script");
    js.type = "module";
    js.src = src;
    head.appendChild(js);
  
  // Push script to array
  scripts.push(src);
}

function showHome() {
    insertScript('./j1.js');
}

function showAbout() {
    insertScript('./j2.js');
}

Alternative unique script injection strategies and ideas:

  • Use ES6 Map() to track unique script sources being injected
  • Perhaps only store src to array/dict/map when the script has successfully loaded

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Using Event Listeners (Javascript, jQuery) to change BG color to a random color?

分類Dev

Very simple javascript loop to create event listeners, returning undefined?

分類Dev

Adding event listeners to dynamically added elements using jQuery

分類Dev

How to load contents of multiple files in particular order with Javascript/AJAX

分類Dev

How do I preserve event listeners after sort?

分類Dev

How to load multiple js files to database using mongo shell?

分類Dev

How to trigger window resize event using vanilla javascript?

分類Dev

How to detect volume up button click event using javascript?

分類Dev

How to save click event to HTML form using Javascript

分類Dev

How to pass the text pasted in a textbox to javascript function using onPaste event?

分類Dev

action listeners and event sources in Swing

分類Dev

Way to disable sqlalchemy event listeners

分類Dev

Tests for Event Listeners sendin email

分類Dev

Relationship between Event Listeners and Handlers

分類Dev

Placing event listeners on individual cookies

分類Dev

Adding event listeners and internationalisation in DataTables

分類Dev

Why are the icon classes not getting changed when using event listeners to detect changes?

分類Dev

How to reference "this" within anonymous listeners when using short notation?

分類Dev

Load Page to Iframe with using javascript

分類Dev

Is it too expensive to add and remove event listeners on every call of my React custom hook? How to avoid it?

分類Dev

How can I upload multiple files using JavaScript and FastAPI?

分類Dev

How can I load my last tabs into Chrome using Last Tabs, Last Session files?

分類Dev

javascript : how to change "this" scope on an event

分類Dev

How to stop javascript onclick event

分類Dev

Default TaskExecutor implementation for Async event listeners

分類Dev

Best practices for where to add event listeners

分類Dev

naming a function and adding event listeners to it causes "not defined"

分類Dev

DOM changes stop touch event listeners

分類Dev

Creating Event Listeners to Delete Objects from localStorage

Related 関連記事

  1. 1

    Using Event Listeners (Javascript, jQuery) to change BG color to a random color?

  2. 2

    Very simple javascript loop to create event listeners, returning undefined?

  3. 3

    Adding event listeners to dynamically added elements using jQuery

  4. 4

    How to load contents of multiple files in particular order with Javascript/AJAX

  5. 5

    How do I preserve event listeners after sort?

  6. 6

    How to load multiple js files to database using mongo shell?

  7. 7

    How to trigger window resize event using vanilla javascript?

  8. 8

    How to detect volume up button click event using javascript?

  9. 9

    How to save click event to HTML form using Javascript

  10. 10

    How to pass the text pasted in a textbox to javascript function using onPaste event?

  11. 11

    action listeners and event sources in Swing

  12. 12

    Way to disable sqlalchemy event listeners

  13. 13

    Tests for Event Listeners sendin email

  14. 14

    Relationship between Event Listeners and Handlers

  15. 15

    Placing event listeners on individual cookies

  16. 16

    Adding event listeners and internationalisation in DataTables

  17. 17

    Why are the icon classes not getting changed when using event listeners to detect changes?

  18. 18

    How to reference "this" within anonymous listeners when using short notation?

  19. 19

    Load Page to Iframe with using javascript

  20. 20

    Is it too expensive to add and remove event listeners on every call of my React custom hook? How to avoid it?

  21. 21

    How can I upload multiple files using JavaScript and FastAPI?

  22. 22

    How can I load my last tabs into Chrome using Last Tabs, Last Session files?

  23. 23

    javascript : how to change "this" scope on an event

  24. 24

    How to stop javascript onclick event

  25. 25

    Default TaskExecutor implementation for Async event listeners

  26. 26

    Best practices for where to add event listeners

  27. 27

    naming a function and adding event listeners to it causes "not defined"

  28. 28

    DOM changes stop touch event listeners

  29. 29

    Creating Event Listeners to Delete Objects from localStorage

ホットタグ

アーカイブ