我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?


当前回答

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

其他回答

如果您正在使用 Web 工作者,并希望在工作者的范围内添加额外的脚本,则其他关于添加脚本到标签标签等的答案不会为您工作。

幸运的是,网页工作者有自己的 importScripts 功能,这是在网页工作者的范围内的全球功能,原生于浏览器本身,因为它是规格的一部分。

否则,因为第二个最高的投票答案突出你的问题,RequireJS也可以处理包括在WebWorker内部的脚本(可能称之为ImportScripts本身,但有几个其他有用的功能)。

我基本上做如下,创建一个新的元素,并添加它来主导:

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

在 jQuery 中:

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // Script is now loaded and executed.
    // Put your dependent JavaScript code here.
});

最好使用 jQuery 方式. 要延迟已准备的事件,首先拨打 $.holdReady(真实)。

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});

如果你发现有两个或多个脚本在被召唤时占据相同功能,我们不能同时包含它们,我们需要通过用户选择进行动态操作。

在 jQuery 中的另一个文件使用 $.getScript 工作,因为脚本不会默认隐藏。

HTML

<select class="choice">
  <option value="script1" selected>Script-1</option>
  <option value="script2">Script-2</option>
</select>

雅各布斯

$(".choice").change(on_change);

var url = "https://example.com";
$.url1 = url + "/script1.js";
$.url2 = url + "/script2.js";

function on_change() {
  if ($(".choice").val()=="script1") {
    script1();
  } else {
    script2();
  }
}

// script1
function script1() {
  $.getScript($.url1, function( data, textStatus, jqxhr ) {
    // Execute here
  });
}

// script2
function script2() {
  $.getScript($.url2, function( data, textStatus, jqxhr ) {
    // Execute here
  });
}

我用另一种方法尝试了这个问题。

命令导入脚本,在这里没有效应。

標籤:HTML

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Trials</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="main.js"></script>
    <script src="scriptA.js"></script>
</head>

<body>
<h3>testing js in js (check console logs)</h3>
<button onclick="fnClick()">TEST</button>
</body>

</html>

主.js

function fnClick() {
  console.log('From\tAAAAA');
  var pro = myExpo.hello();
  console.log(pro);
}

编辑:JS

myExpo = {
    hello: function () {
        console.log('From\tBBBBB');
        return "Hello";
    }
}

而结果是

From    AAAAA
From    BBBBB
Hello