简体   繁体   English

从javascript调用file.js

[英]call a file.js from a javascript

Consider the two following files: 考虑以下两个文件:

// main.js
Somescript();

Call the mod.js here

Somescript();

and

//mod.js
alert('a');

How can I call the file mod.js to run in main.js file ? 如何调用文件mod.js在main.js文件中运行?

Implement those "files" as modules and bundle them using a module bundler like browserify or webpack. 将这些“文件”实现为模块,并使用模块捆绑器(如browserify或webpack)将其捆绑。

The simple solution is to make your mod.js module globally available to your main module by adding to the window object: 一个简单的解决方案是通过添加到window对象,使您的mod.js模块在全局上可用于您的主模块:

// mod.js, define
window.myModule = () => alert('a');

// main.js, execute
window.myModule();

You can: 您可以:

1) Use a library like require.js to dynamically require JS files. 1)使用require.js之类的库动态要求JS文件。

2) Define your mod.js code wrapped inside a main function. 2)定义包装在主函数中的mod.js代码。 Import inside the page your mod.js before your main.js and inside your main simply call your function defined in the mod.js 在您的main.js之前和您的main内部之前将mod.js导入页面内,只需调用在mod.js中定义的函数

<script type="text/javascript" src="mod.js"></script>
<script type="text/javascript" src="main.js"></script>

Your mod.js would be something like 您的mod.js就像

function myFunction() {
  // all the mod.js code I want to execute 
}

Your main.js: 您的main.js:

Somescript();

myFunction();

Somescript();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM