如何在另一个javascript文件中包含javascript文件?

vuktfyat  于 2021-09-23  发布在  Java
关注(0)|答案(14)|浏览(300)

javascript中是否有类似的东西 @import 在css中,允许您在另一个javascript文件中包含一个javascript文件?

u59ebvdq

u59ebvdq1#

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

ngynwnxp2#

这里显示的大多数解决方案都意味着动态载荷。我在找一个编译器,哪个混蛋

3pvhb19x

3pvhb19x3#

我刚刚编写了以下javascript代码(使用原型进行dom操作):

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.

7vux5j2d

7vux5j2d4#

如果您想在纯javascript中使用它,可以使用 document.write .

document.write('<script src="myscript.js" type="text/javascript"></script>');

如果使用jquery库,则可以使用 $.getScript 方法。

$.getScript("another_script.js");
bfnvny8b

bfnvny8b5#

以下是facebook为其无处不在的按钮所做的概括版本:

<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);
</script>

如果它适用于facebook,它也适用于你。
我们为什么要找第一个 script 元素而不是 headbody 这是因为有些浏览器不创建一个如果丢失,但我们保证有一个 script 元素-这一个。阅读更多http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/.

zqry0prt

zqry0prt6#

有个好消息要告诉你。很快,您将能够轻松加载javascript代码。它将成为导入javascript代码模块的标准方式,并将成为核心javascript本身的一部分。
你只需要写 import cond from 'cond.js'; 加载名为 cond 从文件中 cond.js .
因此,您不必依赖任何javascript框架,也不必显式地进行ajax调用。
参考:
静态模块分辨率
模块装载机

izj3ouym

izj3ouym7#

陈述 import 在ecmascript 6中。
语法

import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import name , { member [ , [...] ] } from "module-name";
import "module-name" as name;
eanckbw9

eanckbw98#

也许您可以使用我在本页上找到的这个函数。如何在javascript文件中包含javascript文件

function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';

    head.appendChild(script)
}
amrnrhlw

amrnrhlw9#

以下是不带jquery的同步版本:

function myRequire( url ) {
    var ajax = new XMLHttpRequest();
    ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
    ajax.onreadystatechange = function () {
        var script = ajax.response || ajax.responseText;
        if (ajax.readyState === 4) {
            switch( ajax.status) {
                case 200:
                    eval.apply( window, [script] );
                    console.log("script loaded: ", url);
                    break;
                default:
                    console.log("ERROR: script not loaded: ", url);
            }
        }
    };
    ajax.send(null);
}

请注意,要使此跨域工作,服务器需要设置 allow-origin 响应中的标题。

a64a0gku

a64a0gku10#

如果有人想找更高级的东西,试试requirejs。您将获得额外的好处,如依赖关系管理、更好的并发性和避免重复(即多次检索脚本)。
您可以在“模块”中编写javascript文件,然后在其他脚本中将它们作为依赖项引用。或者您可以使用requirejs作为简单的“获取此脚本”解决方案。
例子:
将依赖项定义为模块:
some-dependency.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是依赖于some-dependency.js的“主”javascript文件

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

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

摘自github自述:
requirejs加载普通javascript文件以及更多定义的模块。它针对浏览器中的使用进行了优化,包括在web worker中,但也可以在其他javascript环境中使用,如rhino和node。它实现了异步模块api。
requirejs使用纯脚本标记加载模块/文件,因此它应该允许轻松调试。它可以简单地用于加载现有的javascript文件,因此您可以将其添加到现有项目中,而无需重新编写javascript文件。
...

gab6jxml

gab6jxml11#

实际上,有一种方法可以非异步加载javascript文件,因此您可以在加载新加载的文件后立即使用其中包含的函数,我认为它适用于所有浏览器。
你需要使用 jQuery.append()<head> 元素,即:

$("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错误控制台和chrome开发者工具)将错误地报告其位置,如果您使用firebug跟踪javascript错误很多,这是一个大问题(我知道)。firebug由于某种原因根本不知道新加载的文件,因此如果该文件中发生错误,它会报告它发生在主html文件中,您将很难找到错误的真正原因。
但是如果这对你来说不是问题,那么这个方法应该是有效的。
实际上,我已经编写了一个名为$.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');

在这个例子中,我也做了一个简单的测试。
它包括一个 main.js 在主html中输入文件,然后在中输入脚本 main.js 使用 $.import_js() 要导入名为 included.js ,它定义了此函数:

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

包括 included.js 这个 hello() 函数被调用,您将得到警报。
(这是对e-satis评论的回应)。

kxkpmulp

kxkpmulp12#

在我看来,另一种更干净的方法是发出同步ajax请求,而不是使用 <script> 标签。这也是node.js处理include的方式。
下面是一个使用jquery的示例:

function require(script) {
    $.ajax({
        url: script,
        dataType: "script",
        async: false,           // <-- This is the key
        success: function () {
            // all good...
        },
        error: function () {
            throw new Error("Could not load script " + script);
        }
    });
}

然后,您可以像通常使用include一样在代码中使用它:

require("/scripts/subscript.js");

并且能够从下一行中所需的脚本调用函数:

subscript.doSomethingCool();
0yg35tkg

0yg35tkg13#

可以动态生成javascript标记,并从其他javascript代码内部将其附加到html文档中。这将加载目标javascript文件。

function includeJs(jsFilePath) {
    var js = document.createElement("script");

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

    document.body.appendChild(js);
}

includeJs("/path/to/some/file.js");
z18hc3ub

z18hc3ub14#

javascript的旧版本没有导入、包含或要求,因此开发了许多不同的方法来解决这个问题。
但自2015年(es6)以来,javascript已经有了es6模块标准来在node.js中导入模块,这也是大多数现代浏览器所支持的。
为了与旧浏览器兼容,可以使用webpack和rollup等构建工具和/或babel等透明工具。

es6模块

从v8.5开始,node.js中就支持ecmascript(es6)模块,其中 --experimental-modules 标志,并且因为至少node.js v13.8.0没有该标志。要启用“esm”(与node.js以前的commonjs样式模块系统[“cjs”]),您可以使用 "type": "module" 在里面 package.json 或者为文件提供扩展名 .mjs . (类似地,可以命名使用node.js以前的cjs模块编写的模块 .cjs 如果默认设置为esm。)
使用 package.json :

{
    "type": "module"
}

然后 module.js :

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

然后 main.js :

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

使用 .mjs ,你会的 module.mjs :

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

然后 main.mjs :

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

浏览器中的ecmascript模块

自safari 10.1、chrome 61、firefox 60和edge 16以来,浏览器一直支持直接加载ecmascript模块(不需要像webpack这样的工具)。请查看caniuse当前的支持情况。没有必要使用node.js' .mjs 扩展;浏览器完全忽略模块/脚本上的文件扩展名。

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

阅读更多https://jakearchibald.com/2017/es-modules-in-browsers/

浏览器中的动态导入

动态导入允许脚本根据需要加载其他脚本:

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

阅读更多https://developers.google.com/web/updates/2017/11/dynamic-import

node.js需要

在node.js中仍然广泛使用的较旧的cjs模块样式是 module.exports / require 系统。

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

javascript还有其他方法可以在不需要预处理的浏览器中包含外部javascript内容。

ajax加载

您可以通过ajax调用加载其他脚本,然后使用 eval 运行它。这是最简单的方法,但由于javascript沙盒安全模型,它仅限于您的域。使用 eval 同时也打开了漏洞、黑客和安全问题的大门。

提取装载

与动态导入一样,您可以使用 fetch 使用承诺调用,以使用fetch inject库控制脚本依赖项的执行顺序:

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加载

jquery库在一行中提供了加载功能:

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

动态脚本加载

您可以将带有脚本url的脚本标记添加到html中。为了避免jquery的开销,这是一个理想的解决方案。
脚本甚至可以驻留在不同的服务器上。此外,浏览器还会评估代码。这个 <script> 标签可以被注入到任何一个网页中 <head> ,或在关闭前插入 </body> 标签。
下面是一个如何工作的示例:

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)
}

此函数将添加一个新的 <script> 标记到页面标题部分的末尾,其中 src 属性设置为作为第一个参数提供给函数的url。
这两种解决方案都在javascript疯狂:动态脚本加载中进行了讨论和说明。

检测脚本何时执行

现在,有一个大问题你必须知道。这样做意味着您可以远程加载代码。现代web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能(这适用于jquery方法和手动动态脚本加载方法。)
这意味着如果您直接使用这些技巧,您将无法在请求加载代码后的下一行使用新加载的代码,因为它仍在加载。
例如: my_lovely_script.js 包含 MySuperObject :

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

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

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

然后按f5重新加载页面。而且它有效!令人困惑
那怎么办呢?
好吧,你可以使用作者在我给你的链接中建议的黑客。总之,对于匆忙的人,他使用事件在加载脚本时运行回调函数。因此,您可以使用远程库将所有代码放入回调函数中。例如:

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加载的文章讨论了这一点。

源代码合并/预处理

如本答案顶部所述,许多开发人员在其项目中使用构建/传输工具,如parcel、webpack或babel,允许他们使用即将推出的javascript语法,为较旧的浏览器提供向后兼容性,合并文件,缩小,执行代码拆分等。

相关问题