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

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

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

u59ebvdq

u59ebvdq1#

您还可以使用php组装脚本:
文件 main.js.php :

  1. <?php
  2. header('Content-type:text/javascript; charset=utf-8');
  3. include_once("foo.js.php");
  4. include_once("bar.js.php");
  5. ?>
  6. // Main JavaScript code goes here
ngynwnxp

ngynwnxp2#

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

3pvhb19x

3pvhb19x3#

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

  1. var require = (function() {
  2. var _required = {};
  3. return (function(url, callback) {
  4. if (typeof url == 'object') {
  5. // We've (hopefully) got an array: time to chain!
  6. if (url.length > 1) {
  7. // Load the nth file as soon as everything up to the
  8. // n-1th one is done.
  9. require(url.slice(0, url.length - 1), function() {
  10. require(url[url.length - 1], callback);
  11. });
  12. } else if (url.length == 1) {
  13. require(url[0], callback);
  14. }
  15. return;
  16. }
  17. if (typeof _required[url] == 'undefined') {
  18. // Haven't loaded this URL yet; gogogo!
  19. _required[url] = [];
  20. var script = new Element('script', {
  21. src: url,
  22. type: 'text/javascript'
  23. });
  24. script.observe('load', function() {
  25. console.log("script " + url + " loaded.");
  26. _required[url].each(function(cb) {
  27. cb.call(); // TODO: does this execute in the right context?
  28. });
  29. _required[url] = true;
  30. });
  31. $$('head')[0].insert(script);
  32. } else if (typeof _required[url] == 'boolean') {
  33. // We already loaded the thing, so go ahead.
  34. if (callback) {
  35. callback.call();
  36. }
  37. return;
  38. }
  39. if (callback) {
  40. _required[url].push(callback);
  41. }
  42. });
  43. })();

用法:

  1. <script src="prototype.js"></script>
  2. <script src="require.js"></script>
  3. <script>
  4. require(['foo.js','bar.js'], function () {
  5. /* Use foo.js and bar.js here */
  6. });
  7. </script>

主旨:http://gist.github.com/284442.

展开查看全部
7vux5j2d

7vux5j2d4#

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

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

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

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

bfnvny8b5#

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

  1. <script>
  2. var firstScript = document.getElementsByTagName('script')[0],
  3. js = document.createElement('script');
  4. js.src = 'https://cdnjs.cloudflare.com/ajax/libs/Snowstorm/20131208/snowstorm-min.js';
  5. js.onload = function () {
  6. // do stuff with your dynamically loaded script
  7. snowStorm.snowColor = '#99ccff';
  8. };
  9. firstScript.parentNode.insertBefore(js, firstScript);
  10. </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中。
语法

  1. import name from "module-name";
  2. import { member } from "module-name";
  3. import { member as alias } from "module-name";
  4. import { member1 , member2 } from "module-name";
  5. import { member1 , member2 as alias2 , [...] } from "module-name";
  6. import name , { member [ , [...] ] } from "module-name";
  7. import "module-name" as name;
eanckbw9

eanckbw98#

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

  1. function include(filename)
  2. {
  3. var head = document.getElementsByTagName('head')[0];
  4. var script = document.createElement('script');
  5. script.src = filename;
  6. script.type = 'text/javascript';
  7. head.appendChild(script)
  8. }
amrnrhlw

amrnrhlw9#

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

  1. function myRequire( url ) {
  2. var ajax = new XMLHttpRequest();
  3. ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
  4. ajax.onreadystatechange = function () {
  5. var script = ajax.response || ajax.responseText;
  6. if (ajax.readyState === 4) {
  7. switch( ajax.status) {
  8. case 200:
  9. eval.apply( window, [script] );
  10. console.log("script loaded: ", url);
  11. break;
  12. default:
  13. console.log("ERROR: script not loaded: ", url);
  14. }
  15. }
  16. };
  17. ajax.send(null);
  18. }

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

展开查看全部
a64a0gku

a64a0gku10#

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

  1. define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {
  2. //Your actual script goes here.
  3. //The dependent scripts will be fetched if necessary.
  4. return libraryObject; //For example, jQuery object
  5. });

implementation.js是依赖于some-dependency.js的“主”javascript文件

  1. require(['some-dependency'], function(dependency) {
  2. //Your script goes here
  3. //some-dependency.js is fetched.
  4. //Then your script is executed
  5. });

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

展开查看全部
gab6jxml

gab6jxml11#

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

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

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

  1. (function($)
  2. {
  3. /*
  4. * $.import_js() helper (for JavaScript importing within JavaScript code).
  5. */
  6. var import_js_imported = [];
  7. $.extend(true,
  8. {
  9. import_js : function(script)
  10. {
  11. var found = false;
  12. for (var i = 0; i < import_js_imported.length; i++)
  13. if (import_js_imported[i] == script) {
  14. found = true;
  15. break;
  16. }
  17. if (found == false) {
  18. $("head").append($('<script></script').attr('src', script));
  19. import_js_imported.push(script);
  20. }
  21. }
  22. });
  23. })(jQuery);

因此,要导入javascript,您只需执行以下操作:

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

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

  1. function hello()
  2. {
  3. alert("Hello world!");
  4. }

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

展开查看全部
kxkpmulp

kxkpmulp12#

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

  1. function require(script) {
  2. $.ajax({
  3. url: script,
  4. dataType: "script",
  5. async: false, // <-- This is the key
  6. success: function () {
  7. // all good...
  8. },
  9. error: function () {
  10. throw new Error("Could not load script " + script);
  11. }
  12. });
  13. }

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

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

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

  1. subscript.doSomethingCool();
展开查看全部
0yg35tkg

0yg35tkg13#

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

  1. function includeJs(jsFilePath) {
  2. var js = document.createElement("script");
  3. js.type = "text/javascript";
  4. js.src = jsFilePath;
  5. document.body.appendChild(js);
  6. }
  7. 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 :

  1. {
  2. "type": "module"
  3. }

然后 module.js :

  1. export function hello() {
  2. return "Hello";
  3. }

然后 main.js :

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

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

  1. export function hello() {
  2. return "Hello";
  3. }

然后 main.mjs :

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

浏览器中的ecmascript模块

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

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

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

浏览器中的动态导入

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

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

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

node.js需要

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

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

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

ajax加载

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

提取装载

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

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

jquery加载

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

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

动态脚本加载

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

  1. function dynamicallyLoadScript(url) {
  2. var script = document.createElement("script"); // create a script DOM node
  3. script.src = url; // set its src to the provided URL
  4. 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)
  5. }

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

检测脚本何时执行

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

  1. var js = document.createElement("script");
  2. js.type = "text/javascript";
  3. js.src = jsFilePath;
  4. document.body.appendChild(js);
  5. var s = new MySuperObject();
  6. Error : MySuperObject is undefined

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

  1. function loadScript(url, callback)
  2. {
  3. // Adding the script tag to the head as suggested before
  4. var head = document.head;
  5. var script = document.createElement('script');
  6. script.type = 'text/javascript';
  7. script.src = url;
  8. // Then bind the event to the callback function.
  9. // There are several events for cross browser compatibility.
  10. script.onreadystatechange = callback;
  11. script.onload = callback;
  12. // Fire the loading
  13. head.appendChild(script);
  14. }

然后编写脚本加载到lambda函数后要使用的代码:

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

然后运行所有这些:

  1. loadScript("my_lovely_script.js", myPrettyCode);

请注意,脚本可能在加载dom之后执行,也可能在加载之前执行,具体取决于浏览器以及是否包含该行 script.async = false; . 有一篇关于javascript加载的文章讨论了这一点。

源代码合并/预处理

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

展开查看全部

相关问题