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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9037082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:24:17  来源:igfitidea点击:

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

javascript

提问by seven_swodniw

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.

让我问一下是否可以在运行时将 javascript 代码加载到 html 文件中。例如,放置一个文本框来输入脚本文件的位置和一个表单按钮来触发加载脚本文件。

Thank you in advance.

先感谢您。

回答by

Paste this within onclick of that button (correct the url in 3rd line):

将此粘贴到该按钮的 onclick 中(更正第 3 行中的网址):

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

回答by Rich O'Kelly

Yes, the jQuery getScript methodmakes 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);

回答by DamirR

All good answers above. You can also load js via ajax as any other html fragment. Short example:

以上都是很好的答案。您还可以像任何其他 html 片段一样通过 ajax 加载 js。简短示例:

start.html

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

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 - 我只是将它用作概念的快速证明。

回答by JINO SHAJI

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').