我如何在另一个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 );
            },
        } );

使用的例子

其他回答

是的,有......

在 ES6 中,我们可以将部分或整个JavaScript文件导出并导入到另一个文件中。

但等待,ES6不支持所有浏览器,所以你需要通过 babel.js 使用它,例如...

所以你创建一个类如下:

class Person {
  constructor(name) {
    this.name = name;
  }

  build() {
    return new Person(this);
  }
}

module.exports = Person;

import { Person } from 'Person';

您也可以要求文件如:

const Person = require('./Person');

如果您正在使用更古老的 JavaScript 版本,您可以使用 requirejs:

requirejs(["helper/util"], function(util) {
    // This function is called when scripts/helper/util.js is loaded.
    // If util.js calls define(), then this function is not fired until
    // util's dependencies have loaded, and the util argument will hold
    // the module value for "helper/util".
});

如果你想坚持旧版本的物品,如jQuery,你也可以使用一些东西,如 getScript:

jQuery.getScript('./another-script.js', function() {
    // Call back after another-script loaded
});

最后,但不要忘记,你可以用 <script> 标签一起编写脚本的传统方式。

<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>

注意: 有几种方式可以执行一个外部脚本: 如果 async 存在: 脚本与页面剩余的同步执行(脚本将执行,而页面继续播放) 如果 async 没有存在,并且 defer 存在: 脚本在页面完成播放时执行 如果没有 async 或 defer 存在: 脚本被捕并执行 imme

$("head").append($("<script></script>").attr("src", url));

/* Note that following line of code is incorrect because it doesn't escape the
 * HTML attribute src correctly and will fail if `url` contains special characters:
 * $("head").append('<script src="' + url + '"></script>');
 */

但是,这个方法也有一个问题:如果一个错误发生在进口的JavaScript文件,Firebug(以及Firefox Error Console和Chrome Developer Tools也)将报告其位置错误,这是一个很大的问题,如果你使用Firebug跟踪JavaScript错误很多(我做)。

但是,如果这不是一个问题,那么这个方法应该工作。

我實際上寫了一個名為 $.import_js() 的 jQuery 插件,使用此方法:

(function($)
{
    /*
     * $.import_js() helper (for JavaScript importing within JavaScript code).
     */
    var import_js_imported = [];
    
    $.extend(true,
    {
        import_js : function(script)
        {
            var found = false;
            for (var i = 0; i < import_js_imported.length; i++)
                if (import_js_imported[i] == script) {
                    found = true;
                    break;
                }
            
            if (found == false) {
                $("head").append($('<script></script').attr('src', script));
                import_js_imported.push(script);
            }
        }
    });
    
})(jQuery);

因此,所有你需要做才能进口JavaScript是:

$.import_js('/path_to_project/scripts/somefunctions.js');

我也做了一个简单的测试为这个例子。

它包含主.js 文件在主 HTML 中,然后在主.js 中的脚本使用 $.import_js() 来导入一个名为 included.js 的额外文件,该文件定义了此功能:

function hello()
{
    alert("Hello world!");
}

(这个答案是回复e-satis的评论)。

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

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

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

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

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

不要忘了查看LAB.js!

<script type="text/javascript">
  $LAB.script("jquery-1.8.3.js").wait().script("scripts/clientscript.js");      
</script>
var js = document.createElement("script");

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

document.body.appendChild(js);