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


当前回答

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

其他回答

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

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

document.body.appendChild(js);

$("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的评论)。

下面是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代码. 它将成为进口JavaScript代码的标准方式,并将是核心JavaScript本身的一部分。

您只需要从“cond.js”中输入代码;从“cond.js”文件中加载一个名为 macro 的代码。

因此,您不需要依靠任何JavaScript框架,也不需要明确进行Ajax通话。

提到:

静态模块分辨率模块充电器

还有 Head.js. 很容易处理:

head.load("js/jquery.min.js",
          "js/jquery.someplugin.js",
          "js/jquery.someplugin.css", function() {
  alert("Everything is ok!");
});

正如你所看到的,它比 Require.js 更容易,而且像 jQuery 的 $.getScript 方法一样方便,它还有一些先进的功能,如条件加载、功能检测等。