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


当前回答

雖然這些答案很棒,但有一個簡單的「解決方案」已經存在,因為脚本充電存在,它將覆蓋大多數人使用案例的99.999%。

<!DOCTYPE HTML>
<html>
    <head>
        <script src="script1.js"></script>
        <script src="script2.js"></script>
    </head>
    <body></body>
</html>

如果脚本2需要脚本1,这实际上是做这样的事情的绝对最简单的方式,我很惊讶,没有人带来了这一点,因为这是最明显和最简单的答案,几乎每个案例都会适用。

其他回答

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

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

可以动态地创建一个JavaScript标签并将其添加到来自其他JavaScript代码的HTML文档中,这将加载针对JavaScript文件。

function includeJs(jsFilePath) {
    var js = document.createElement("script");

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

    document.body.appendChild(js);
}

includeJs("/path/to/some/file.js");

我只是写了这个JavaScript代码(使用DOM操作的Prototype):

var require = (function() {
    var _required = {};
    return (function(url, callback) {
        if (typeof url == 'object') {
            // We've (hopefully) got an array: time to chain!
            if (url.length > 1) {
                // Load the nth file as soon as everything up to the
                // n-1th one is done.
                require(url.slice(0, url.length - 1), function() {
                    require(url[url.length - 1], callback);
                });
            } else if (url.length == 1) {
                require(url[0], callback);
            }
            return;
        }
        if (typeof _required[url] == 'undefined') {
            // Haven't loaded this URL yet; gogogo!
            _required[url] = [];

            var script = new Element('script', {
                src: url,
                type: 'text/javascript'
            });
            script.observe('load', function() {
                console.log("script " + url + " loaded.");
                _required[url].each(function(cb) {
                    cb.call(); // TODO: does this execute in the right context?
                });
                _required[url] = true;
            });

            $$('head')[0].insert(script);
        } else if (typeof _required[url] == 'boolean') {
            // We already loaded the thing, so go ahead.
            if (callback) {
                callback.call();
            }
            return;
        }

        if (callback) {
            _required[url].push(callback);
        }
    });
})();

使用:

<script src="prototype.js"></script>
<script src="require.js"></script>
<script>
    require(['foo.js','bar.js'], function () {
        /* Use foo.js and bar.js here */
    });
</script>

地址: http://gist.github.com/284442.

下面是Facebook如何为其微妙的Like按钮进行的一般版本:

<script> var firstScript = document.getElementsByTagName('script')[0], js = document.createElement('script'); js.src = 'https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js'; js.onload = function () { // do stuff with your dynamically loaded script snowStorm.snowColor = '#99ccff'; }; firstScript.parentNode.insertBefore(js, firstScript); </sc

如果它为Facebook工作,它会为你工作。

为什么我们正在寻找第一个脚本元素而不是头部或身体是因为一些浏览器不会创建一个如果缺乏,但我们保证有一个脚本元素 - 这个一个。

如果你想要它在纯粹的JavaScript,你可以使用document.write。

document.write('<script src="myscript.js" type="text/javascript"></script>');

如果您使用 jQuery 图书馆,您可以使用 $.getScript 方法。

$.getScript("another_script.js");