0

I would like to know if there is a method to importing scripts from javascript script to another javascript script.

For example,

import script.js //obviously it is wrong.

Lets say on script 1:

function hello(){
  console.log(1+2);
}

I would like to use the functions defined in script 1 on script 2.

Therefore, script 2 should have:

 hello();

And should produce this on the webpage:

3

I went to research for answers, yet i do not understand the codes. Can someone explain it, step by step?

4
  • 1
    Which answers did you look at that you didn't understand? Commented Nov 28, 2013 at 1:39
  • document.getElementsByTagName("body") Commented Nov 28, 2013 at 1:39
  • and body.appendChild(script) Commented Nov 28, 2013 at 1:40
  • funny how what was obviously wrong a while ago is now borderline right! Commented Nov 9, 2022 at 23:37

3 Answers 3

1
var script = document.createElement("script");

script.src = "script1.js"; // set the url of script you want

var body = document.getElementsByTagName("body")[0];

body.appendChild(script); // append script to body will load the script and execute it
Sign up to request clarification or add additional context in comments.

1 Comment

Thats it! Thanks for explaining too!
1

Javascript is loaded via the <script> tag

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

For more advanced Javascript loading, you can use RequireJS

See http://requirejs.org/docs/start.html

2 Comments

I mean importing from a javascript to a javascript.
Sounds like requirejs
0

You can import it dynamically:

http://api.jquery.com/jQuery.getScript/

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

1 Comment

if you will create jsFiddle for your code, i'll will help you with it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.