我如何在另一个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
推荐文章
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?
- 如何使用JavaScript重新加载ReCaptcha ?
- jQuery。由于转义了JSON中的单引号,parseJSON抛出“无效JSON”错误
- 在JavaScript关联数组中动态创建键
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?