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


当前回答

这就是简单的:

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

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

document.body.appendChild(js);

其他回答

不要忘了查看LAB.js!

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

我有一个简单的问题,但我被这个问题的答案震惊。

我不得不使用一个变量(myVar1)定义在一个JavaScript文件(myvariables.js)在另一个JavaScript文件(main.js)。

為此,我做了下面的:

在 HTML 文件中下载了 JavaScript 代码,在正确的顺序中, myvariables.js 首先,然后 main.js:

<html>
    <body onload="bodyReady();" >

        <script src="myvariables.js" > </script>
        <script src="main.js" > </script>

        <!-- Some other code -->
    </body>
</html>

文件: myvariables.js

var myVar1 = "I am variable from myvariables.js";

文件: main.js

// ...
function bodyReady() {
    // ...
    alert (myVar1);    // This shows "I am variable from myvariables.js", which I needed
    // ...
}
// ...

正如你所看到的,我在另一个JavaScript文件中使用了一个变量,但我不需要将一个添加到另一个文件中,我只需要确保第一个JavaScript文件在第二个JavaScript文件之前加载,并且,第一个JavaScript文件的变量在第二个JavaScript文件中可用,自动。

这拯救了我的日子,我希望这能帮助我。

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

源代码合并/预处理

保持它好,短,简单,可持续的! :]

// Third-party plugins / script (don't forget the full path is necessary)
var FULL_PATH = '', s =
[
    FULL_PATH + 'plugins/script.js'      // Script example
    FULL_PATH + 'plugins/jquery.1.2.js', // jQuery Library
    FULL_PATH + 'plugins/crypto-js/hmac-sha1.js',      // CryptoJS
    FULL_PATH + 'plugins/crypto-js/enc-base64-min.js'  // CryptoJS
];

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

// Initialize a single load
load('plugins/script.js');

// Initialize a full load of scripts
if (s.length > 0)
{
    for (i = 0; i < s.length; i++)
    {
        load(s[i]);
    }
}

这个代码只是一个短暂的功能例子,可能需要额外的功能功能,以便在任何(或提供)平台上提供完整的支持。

下面是没有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);
}

请注意,为了获得此工作跨域,服务器将需要在其响应中设置允许起源标题。