I would like to load a javascript file in an html document.
I need to do it with a bbutton.
I have two files the "index.html" and "testing.js"
i have to load the whole of the js file.
how could this be possible?
Asked
Active
Viewed 4,718 times
0

Peter Toth
- 678
- 6
- 23
-
1would you please elaborate?.. im having trouble understanding the context of your question. why wouldnt you load the js file normally using a script tag? – Moose Apr 27 '17 at 18:21
3 Answers
6
If you have jQuery loaded in your page, just write the following line:
$.getScript("testing.js");
Otherwise you need to add a script tag as below:
var scriptTag = document.createElement('script');
scriptTag.setAttribute('src','testing.js');
document.head.appendChild(scriptTag)
also you can set async attribute to true as well.
scriptTag.async = true

Siamand
- 1,080
- 10
- 19
1
I do not know the structure of your HTML, but you could do this:
var button = document.getElementsByTagName('button')[0],
script = document.getElementsByTagName('script')[0];
button.addEventListener('click', handler, false);
function handler() {
script.src = 'testing.js';
console.log(script);
}
<button>OK</button>
<script src=""></script>

Badacadabra
- 8,043
- 7
- 28
- 49
1
Alternative (non-jQuery):
document.getElementsByTagName('body')[0].innerHTML += "<script src='testing.js'></script>";
document.getElementsByTagName('body')
gets an array of elements of body tag. [0] selects the first (and only, usually) element of that array.
Next, .innerHTML
accesses the code inside the element (i.e., our only body tag here) and +=
adds the string ("<script src='testing.js'></script>"
) after the HTML already in it. And then the script is loaded.
Overall:
<html>
<head>
<script>
function loadScript() {
document.getElementsByTagName('body')[0].innerHTML += "<script src='testing.js'></script>";
}
</script>
</head>
<body>
<button onclick='loadScript()'></button>
</body>
</html>

Vedaant Arya
- 475
- 6
- 18