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


当前回答

现在,我可能完全被误导了,但这里是我最近开始做的事情......开始和结束你的JavaScript文件与运输返回,在PHP脚本中放置,随后另一个运输返回。

技术上,你不需要评论,但它在Dreamweaver中发布错误,这让我感到不安. 如果你在一个不发布错误的IDE中编写,你不需要评论或运输回来。

\n
//<?php require_once("path/to/javascript/dependency.js"); ?>

function myFunction(){
    // stuff
}
\n

其他回答

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

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

在后端,您可以使用 CommonJS 模块。

//a.js
function func () {
   var result = "OK Bro";
   return result;
}

module.exports = { func };
//b.js
var a = require('./a.js');
console.log(a.func);
var s=["Hscript.js","checkRobert.js","Hscript.js"];
for(i=0;i<s.length;i++){
  var script=document.createElement("script");
  script.type="text/javascript";
  script.src=s[i];
  document.getElementsByTagName("head")[0].appendChild(script)
};

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

是的,有......

在 ES6 中,我们可以将部分或整个JavaScript文件导出并导入到另一个文件中。

但等待,ES6不支持所有浏览器,所以你需要通过 babel.js 使用它,例如...

所以你创建一个类如下:

class Person {
  constructor(name) {
    this.name = name;
  }

  build() {
    return new Person(this);
  }
}

module.exports = Person;

import { Person } from 'Person';

您也可以要求文件如:

const Person = require('./Person');

如果您正在使用更古老的 JavaScript 版本,您可以使用 requirejs:

requirejs(["helper/util"], function(util) {
    // This function is called when scripts/helper/util.js is loaded.
    // If util.js calls define(), then this function is not fired until
    // util's dependencies have loaded, and the util argument will hold
    // the module value for "helper/util".
});

如果你想坚持旧版本的物品,如jQuery,你也可以使用一些东西,如 getScript:

jQuery.getScript('./another-script.js', function() {
    // Call back after another-script loaded
});

最后,但不要忘记,你可以用 <script> 标签一起编写脚本的传统方式。

<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>

注意: 有几种方式可以执行一个外部脚本: 如果 async 存在: 脚本与页面剩余的同步执行(脚本将执行,而页面继续播放) 如果 async 没有存在,并且 defer 存在: 脚本在页面完成播放时执行 如果没有 async 或 defer 存在: 脚本被捕并执行 imme