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


当前回答

最好使用 jQuery 方式. 要延迟已准备的事件,首先拨打 $.holdReady(真实)。

$.holdReady(true);
$.getScript("myplugin.js", function() {
    $.holdReady(false);
});

其他回答

我有要求无同步加载一系列的JavaScript文件,最终进行呼叫回复。

// Load a JavaScript file from other JavaScript file
function loadScript(urlPack, callback) {
    var url = urlPack.shift();
    var subCallback;

    if (urlPack.length == 0) subCallback = callback;
    else subCallback = function () {
        console.log("Log script: " + new Date().getTime());
        loadScript(urlPack, callback);
    }

    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('head')[0];
    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 = subCallback;
    script.onload = subCallback;

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

例子:

loadScript(
[
    "js/DataTable/jquery.dataTables.js",
    "js/DataTable/dataTables.bootstrap.js",
    "js/DataTable/dataTables.buttons.min.js",
    "js/DataTable/dataTables.colReorder.min.js",
    "js/DataTable/dataTables.fixedHeader.min.js",
    "js/DataTable/buttons.bootstrap.min.js",
    "js/DataTable/buttons.colVis.min.js",
    "js/DataTable/buttons.html5.min.js"
], function() { gpLoad(params); });

第二个脚本不会充电,直到第一个完全充电,因此...

结果:

此分類上一篇

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

源代码合并/预处理

我来到这个问题,因为我正在寻找一个简单的方式来保持一个收藏有用的JavaScript插件。

设置一个名为“plugins.js”的文件(或 extensions.js 或任何你想要的)。 保持你的插件文件与一个主文件。

//set array to be updated when we add or remove plugin files
var pluginNames = ["lettering", "fittext", "butterjam", etc.];

//one script tag for each plugin
$.each(pluginNames, function(){
    $('head').append('<script src="js/plugins/' + this + '.js"></script>');
});

手动呼叫你的头中的一个文件: <script src="js/plugins/plugins.js"></script>

但是:

雖然所有插件都落入頭標籤的方式,他們不總是通過瀏覽器,當你點擊到頁面或更新。

此脚本将添加 JavaScript 文件到任何其他 <script> 标签的顶部:

(function () {
    var li = document.createElement('script'); 
    li.type = 'text/javascript'; 
    li.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"; 
    li.async = true; 
    var s = document.getElementsByTagName('script')[0]; 
    s.parentNode.insertBefore(li, s);
})();

如果您打算上传 JavaScript 文件使用所引入/包含的文件中的功能,您也可以定义全球对象,并将功能定义为对象项目。

世界.js

A = {};

文件1JS

A.func1 = function() {
  console.log("func1");
}

文件2JS

A.func2 = function() {
  console.log("func2");
}

主.js

A.func1();
A.func2();

您只需在 HTML 文件中包含脚本时要小心,命令应该如下:

<head>
  <script type="text/javascript" src="global.js"></script>
  <script type="text/javascript" src="file1.js"></script>
  <script type="text/javascript" src="file2.js"></script>
  <script type="text/javascript" src="main.js"></script>
</head>