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


当前回答

如果你想要一个单一的链接到所有的JavaScript功能,它们位于不同的文件,你可以做这样的事情,使用PHP:

创建一个 php 文件,将存储所有的 javascript 功能/triggers javascript.php 并确保它是一个.php 文件:

在你的“头”部分

 <script src="/directory/javascript.php"></script>

在您的 javascript.php 中,创建一个包含内容类型的应用程序/javascript 标题,并使用 php glob 包含所有 javascript 文件/脚本如下:

饰 JavaScript.php

<?php 
header("content-type:application/javascript");
foreach(glob("/functions/*.js") as $filename){include($filename);}
?> 

现在,你可以创建单独的JavaScript文件并将其添加到你的 / 功能文件夹,或者你可以称之为什么。

其他回答

我基本上做如下,创建一个新的元素,并添加它来主导:

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

在 jQuery 中:

// jQuery
$.getScript('/path/to/imported/script.js', function()
{
    // Script is now loaded and executed.
    // Put your dependent JavaScript code here.
});

有一个好消息给你. 很快你将能够轻松地加载JavaScript代码. 它将成为进口JavaScript代码的标准方式,并将是核心JavaScript本身的一部分。

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

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

提到:

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

旧版本的JavaScript没有进口,包括,或要求,所以许多不同的方法对这个问题已经开发。

使用 package.json:

{
    "type": "module"
}

export function hello() {
  return "Hello";
}

import { hello } from './module.js';
let val = hello();  // val is "Hello";

export function hello() {
  return "Hello";
}

此分類上一篇:mjs:

import { hello } from './module.mjs';
let val = hello();  // val is "Hello";

ECMAScript 在浏览器中的模块

<script type="module">
  import { hello } from './hello.mjs'; // Or the extension could be just `.js`
  hello('world');
</script>
// hello.mjs -- or the extension could be just `.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

在浏览器中的动态进口

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

Node.js 需要

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

您可以使用 AJAX 通话加载额外的脚本,然后使用 eval 运行它. 这是最简单的方式,但由于 JavaScript Sandbox 安全模式而仅限于您的域名。

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery 图书馆在一个行中提供充电功能:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

下面是如何工作的例子:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL
   
    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

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

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

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

然后,你写下你想要使用的代码后,脚本被加载到一个Lambda函数:

var myPrettyCode = function() {
   // Here, do whatever you want
};

loadScript("my_lovely_script.js", myPrettyCode);

请注意,在 DOM 已加载后,脚本可以运行,或者在此之前,取决于浏览器,以及您是否包含了行 script.async = false;. 有一个关于JavaScript 加载的一般文章,讨论了这一点。

源代码合并/预处理

这里是一个基本插件,允许您使用 @import “path/to/file.js”; syntax 在任何文件中,包括JavaScript文件。

它可以通过 npm 安装安装: https://npmjs.org/package/grunt-import

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