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


当前回答

您可以使用我的 loadScript ES 模块来加载 JavaScript 文件。

使用:

在您的标签中,包含下列代码:

<script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.js"></script>

<script src="https://raw.githack.com/anhr/loadScriptNodeJS/master/build/loadScript.min.js"></script>

现在,您可以使用 window.loadScript 加载您的 JavaScript 文件。

loadScript.async( src, [选项] )

无同步加载 JavaScript 文件。

src:一个外部脚本文件或脚本文件名序列的URL。

选项:以下选项可用

onload: function () The onload event occurs when a script has been loaded. Default is undefined.

onerror: function ( str, e ) The onerror event occurs when an error has been occurred. The default is undefined.

    str: error details

    e: event

appendTo: The node to which the new script will be append. The default is the head node.

例如

loadScript.async( "JavaScript.js",
        {
            onload: function () {

                var str = 'file has been loaded successfully';
                console.log( str );
            },
            onerror: function ( str, e ) {

                console.error( str );
            },
        } );

使用的例子

其他回答

如果有人正在寻找一些更先进的东西,试试 RequireJS. 你会得到添加的好处,如依赖管理,更好的竞争,并避免复制(即,获得一个脚本超过一次)。

您可以将 JavaScript 文件写入“模块”,然后将其列为其他脚本中的依赖,或者您可以使用 RequireJS 作为一个简单的“去获取这个脚本”解决方案。

例子:

将依赖定义为模块:

某些依赖性.js

define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {

     //Your actual script goes here.   
     //The dependent scripts will be fetched if necessary.

     return libraryObject;  //For example, jQuery object
});

implementation.js 是您的“主要” JavaScript 文件,取决于某些 dependency.js

require(['some-dependency'], function(dependency) {

    //Your script goes here
    //some-dependency.js is fetched.   
    //Then your script is executed
});

從 GitHub README 發表:

RequireJS 加载平面 JavaScript 文件以及更定义的模块. 它是优化在浏览器中的使用,包括在 Web 工作者,但它可以用于其他 JavaScript 环境,如 Rhino 和 Node. 它实施了 Asynchronous 模块 API. RequireJS 使用平面脚本标签加载模块/文件,所以它应该允许轻松的解体。

您也可以使用 PHP 编写脚本:

文件 main.js.php:

<?php
    header('Content-type:text/javascript; charset=utf-8');
    include_once("foo.js.php");
    include_once("bar.js.php");
?>

// Main JavaScript code goes here

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

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

我只是写了这个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.

你不能进口,但你可以参考。

PhpShtorm IDE. 要提到,在一个.js 文件到另一个.js,只需将此添加到文件的顶部:

<reference path="../js/file.js" />

当然,你应该使用自己的PATH到JavaScript文件。

我不知道它是否会在其他IDES中工作,也许是的,只是试试,它也应该在Visual Studio中工作。