1

I have a base.js file that called from my index.html file and this base.js call script script1.js or script2.js according to parameter passed to the base.js file and then I have another script called editor.js will call a function -with the same name but different implementation- from script1.js or script2.js, so my question is how I execute the function after loading the script1.js or script2.js

Samples of what I mean:

index.html

<html>

<head>
    <meta charset="utf-8">
    <title>Rich Text Editor</title>
    <link rel="stylesheet" type="text/css" href="content/css/app-min.css">
</head>

<body>
    <div class="new-question page">
        <p>
            <textarea id="textBox1" class="html-editor" cols="70" rows="10">
                        </textarea>
        </p>
        <p>
            <button id="submit">Submit</button>
        </p>
    </div>
    <script type="text/javascript" src="base.js"></script>
    <script>
        LoadFunction("multiply");
    </script>
    <script type="text/javascript" src="editor.js"></script>
    <script type="text/javascript" src="content/js/script.js"></script>
    <script type="text/javascript" src="content/js/custom-script.js"></script>
</body>

</html>

base.js

let LoadFunction = function (type) {
    //loading localization script
    let script = document.createElement('script');
    script.type = 'text/javascript';
    document.querySelector('body').appendChild(script );
    if(type == "multiply")
       script.src = `script1.js`
   else
       script.src = `script2.js`
}

script1.js

function Calculate(a,b){
return a*b;
}

script2.js

function Calculate(a,b){
return a+b;
}

editor.js

var result = Calculate(5,9);
console.log(result);
2
  • 1
    Amm, maybe using a Promise, so only after the scriptX.js file has been loaded you'd continue with your call of the function (otherwise, it might be undefined as you're calling a function that doesn't exist yet) Commented Jan 11, 2021 at 16:10
  • @OfirBaruch yes exactly it not defined, so would you help me how to achieve this, and thanks for your quick response Commented Jan 11, 2021 at 16:11

1 Answer 1

1

Consider reading more about Promises https://developer.mozilla.org/he/docs/Web/JavaScript/Reference/Global_Objects/Promise

the following is an example using your code, I don't think it fully do what you're looking for (as I called the loadFunction in the editor.js and not in the main file, but I believe this example + the documentation above will help you get the idea). Good luck :)

base.js

let loadFunction = function (type) {
    //loading localization script
    let script = document.createElement('script');
    script.type = 'text/javascript';
    document.querySelector('body').appendChild(script );
    if(type == "multiply")
       script.src = `script1.js`
   else
       script.src = `script2.js`

  // return a promise
  return new Promise((res, rej) => {
    script.onload = function() {
      res();
    }
    script.onerror = function () {
      rej();
    }
  });
}

editor.js

loadFunction('multiple')
  .then(() => {
    // The script file has been loaded.
    // We can use the function.
    var result = Calculate(5,9);
    console.log(result);
  })
  .catch(() => {
    console.error('Could not load the script file.');
  });
  • Haven't fully tested the code.
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I think that the script was loaded but it gave me an error Uncaught SyntaxError: Identifier 'Calculate' has already been declared. I believe that may I wrongly implemented your code so I will go around this to understand that error.
Amm, it's possible that in one session both of the files are being loaded, and in both of them you have a function with the same name. Consider using the variable-function format: let calculate = function () {} instead of function calculate() {}. I believe it will solve the error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.