简体   繁体   English

如何在运行时将 javascript 代码加载到 html 文件?

[英]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.让我问一下是否可以在运行时将 javascript 代码加载到 html 文件中。 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): 将其粘贴到该按钮的onclick中(更正第3行中的URL):

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. 该脚本将在第4行执行后立即开始下载,一旦下载,它将执行或以其他方式可用。

Yes, the jQuery getScript method makes this trivial: 是的, jQuery getScript方法使这个变得微不足道:

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

Alternatively using only native javascript methods: 或者仅使用本机javascript方法:

//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. 您还可以通过ajax加载js作为任何其他html片段。 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. 你不需要为ajax jquery - 我只是用它作为概念的快速证明。

There is also a jquery method here to achieve the same. 这里还有一个jquery方法来实现同样的目的。

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') . 你也可以使用.appendTo('head')

A 1 liner (just for curiosities):一个 1 班轮(仅供好奇):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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