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


当前回答

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

其他回答

您可以使用我的 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 );
            },
        } );

使用的例子

另一个方法是使用HTML进口,这些可以包含脚本参考以及风格表参考。

您可以将 HTML 文件链接到

<link rel="import" href="vendorScripts.html"/>

在 vendorScripts.html 文件中,您可以包含您的脚本参考,如:

<script src="scripts/vendors/jquery.js"></script>
<script src="scripts/vendors/bootstrap.js"></script>
<script src="scripts/vendors/angular.js"></script>
<script src="scripts/vendors/angular-route.js"></script>

查看 HTML Imports 更多详细信息。

不幸的是,它只在Chrome中工作。

也许这里还有另一种方式!

在 Node.js 中,你可以这样做,就像下面的代码一样!

主持人JS

    module.exports = {
      log: function(string) {
        if(console) console.log(string);
      }
      mylog: function(){
        console.log('just for log test!');
      }
    }

主.js

    const mylog = require('./sub');

    mylog.log('Hurray, it works! :)');
    mylog.mylog();

雷夫斯

HTTP://requirejs.org/docs/node.html

如果您使用 Angular,那么一个插件模块 $ocLazyLoad 可以帮助您做到这一点。

以下是其文档的一些引用:

加载一个或多个模块和组件有多个文件: $ocLazyLoad.load([‘testModule.js’,‘testModuleCtrl.js’,‘testModuleService.js’]);加载一个或多个模块有多个文件,并在需要时指定一个类型: 注意: 使用需要JS 风格格格格式(例如,从 js! 开始时),不要指定一个文件扩展。

您也可以使用 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