How to load javascript code in html file at runtime?

Let me ask if it is possible to load javascript code into an html file at runtime. For example, put a text box to enter the location of the script files and the form button to force the script files to load.

Thanks in advance.

+6
source share
4 answers

Paste this inside the onclick of this button (correct the URL in the third line):

var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", "url to the script file here"); document.getElementsByTagName("head")[0].appendChild(script); 

That the script will start loading immediately after line 4 is executed, and as soon as it is loaded, it will be executed or otherwise used.

+15
source

Yes, the jQuery getScript method makes this trivial:

 //on button click event: $.getScript(urlOfScript); 

Alternatively, using only native javascript methods:

 //on button click event: var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'urlOfScript'; head.appendChild(script); 
+7
source

All the good answers are above. You can also load js via ajax like any other html fragment. A brief example:

start.html

 <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> </head> <body> <a href="#" onclick="$('#result').load('start.js'); return false;">start</a> <div id="result"></div> </body> </html> 

start.js

 <script type="text/javascript"> alert('Hello world!'); </script> 

You don't need jquery for ajax - I just used it as a quick proof of concept.

+1
source

It also uses the jquery method to achieve the same.

 let src = 'http://www.example.com/dosome/afsddfa'; $('<script>').attr( { src: src, type: 'text/javascript' }).appendTo('body'); 

It will create a script element and add it to the body.

You can also use .appendTo('head') .

0
source

Source: https://habr.com/ru/post/907052/


All Articles