简体   繁体   中英

How to load javascript code to an html file at runtime?

Let me ask whether it is possible to load javascript code to an html file at runtime. For example , place a textbox to input the location of the script files and a form button to trigger loading the script files.

Thank you in advance.

Paste this within onclick of that button (correct the url in 3rd 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 script will start being downloaded immediately after line 4 is executed, and as soon as it's downloaded it'll execute or otherwise be usable.

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);

All good answers above. You can also load js via ajax as any other html fragment. Short 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 do not need jquery for ajax - I just used it as quick proof of concept.

There is also a jquery method here 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 append it to body.

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

A 1 liner (just for curiosities):

with(document)
with(body)
    with(insertBefore(createElement("script"),firstChild))
        setAttribute("src","//g.alicdn.com/...aplus_v2.js")

//or with additional attributes
with(document)
with(body)
    with(insertBefore(createElement("script"),firstChild))
        setAttribute(
            "exparams","category=...at_bu=cbu",
            id="beacon-aplus",
            src="//g.alicdn.com/...aplus_v2.js")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM