Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

javascript - 如何在另一个JavaScript文件中包含一个JavaScript文件?(How do I include a JavaScript file in another JavaScript file?)

JavaScript中是否有类似于CSS中@import的内容,可让您在另一个JavaScript文件中包含一个JavaScript文件?

  ask by Alec Smart translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.(JavaScript的旧版本没有导入,包含或要求,因此已经开发了许多解决此问题的方法。)

But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers .(但是自2015年(ES6)起,JavaScript就拥有了ES6模块标准,可以在Node.js中导入模块, 大多数现代浏览器也支持该模块。) For compatibility with older browsers, build and/or transpilation tools can be used.(为了与旧版浏览器兼容,可以使用构建和/或编译工具。) ES6 Modules(ES6模块) ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules flag.(自v8.5起,带有--experimental-modules标志的ECMAScript(ES6)模块已在Node.js中得到支持。) All files involved must have the .mjs extension.(涉及的所有文件都必须具有.mjs扩展名。) // module.mjs export function hello() { return "Hello"; } // main.mjs import { hello } from 'module'; // or './module' let val = hello(); // val is "Hello"; ECMAScript modules in browsers(浏览器中的ECMAScript模块) Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse .( Safari 10.1,Chrome 61,Firefox 60和Edge 16开始,浏览器已经支持直接加载ECMAScript模块(不需要像Webpack这样的工具)。请在caniuse上查看当前支持。) <script type="module"> import { hello } from './hello.mjs'; hello('world'); </script> // hello.mjs export function hello(text) { const div = document.createElement('div'); div.textContent = `Hello ${text}`; document.body.appendChild(div); } Read more at https://jakearchibald.com/2017/es-modules-in-browsers/(在https://jakearchibald.com/2017/es-modules-in-browsers/了解更多) Dynamic imports in browsers(浏览器中的动态导入) Dynamic imports let the script load other scripts as needed:(动态导入使脚本可以根据需要加载其他脚本:) <script type="module"> import('hello.mjs').then(module => { module.hello('world'); }); </script> Read more at https://developers.google.com/web/updates/2017/11/dynamic-import(前往https://developers.google.com/web/updates/2017/11/dynamic-import进一步了解) Node.js require(Node.js要求) The old style of importing modules, still widely used in Node.js, is the module.exports/require system.(仍然在Node.js中广泛使用的旧式导入模块是module.exports / require系统。) // mymodule.js module.exports = { hello: function() { return "Hello"; } } // server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is "Hello" There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.(JavaScript还有其他方法可以在不需要预处理的浏览器中包含外部JavaScript内容。) AJAX Loading(AJAX加载) You could load an additional script with an AJAX call and then use eval to run it.(您可以使用AJAX调用加载其他脚本,然后使用eval运行它。) This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model.(这是最直接的方法,但是由于JavaScript沙箱安全模型,它仅限于您的域。) Using eval also opens the door to bugs, hacks and security issues.(使用eval还打开了漏洞,黑客和安全问题的大门。) Fetch Loading(获取加载) Like Dynamic Imports you can load one or many scripts with a fetch call using promises to control order of execution for script dependencies using the Fetch Inject library:(像动态导入一样,您可以使用承诺通过Fetch Inject库控制对脚本依赖项的执行顺序,从而通过fetch调用来加载一个或多个脚本:) 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 Loading(jQuery加载) The jQuery library provides loading functionality in one line :(jQuery在一行中提供了加载功能:) $.getScript("my_lovely_script.js", function() { alert("Script loaded but not necessarily executed."); }); Dynamic Script Loading(动态脚本加载) You could add a script tag with the script URL into the HTML.(您可以将带有脚本URL的脚本标签添加到HTML中。) To avoid the overhead of jQuery, this is an ideal solution.(为了避免jQuery的开销,这是一个理想的解决方案。) The script can even reside on a different server.(该脚本甚至可以驻留在其他服务器上。) Furthermore, the browser evaluates the code.(此外,浏览器会评估代码。) The <script> tag can be injected into either the web page <head> , or inserted just before the closing </body> tag.(可以将<script>标记插入网页<head> ,也可以将其插入在结束</body>标记之前。) Here is an example of how this could work:(这是一个如何工作的示例:) 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) } This function will add a new <script> tag to the end of the head section of the page, where the src attribute is set to the URL which is given to the function as the first parameter.(此函数将在页面头部的末尾添加一个新的<script>标记,其中src属性设置为该函数作为第一个参数给出的URL。) Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading .(在JavaScript Madness:动态脚本加载中讨论和说明了这两种解决方案。) Detecting when the script has been executed(检测何时执行脚本) Now, there is a big issue you must know about.(现在,您必须知道一个大问题。) Doing that implies that you remotely load the code .(这样做意味着您需要远程加载代码 。) Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance.(现代的Web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能。) (This applies to both the jQuery method and the manual dynamic script loading method.)((这适用于jQuery方法和手动动态脚本加载方法。)) It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded , because it will be still loading.(这意味着,如果您直接使用这些技巧, 则在要求加载新代码之后将无法在下一行使用新加载的代码 ,因为它仍将加载。) For example: my_lovely_script.js contains MySuperObject :(例如: my_lovely_script.js包含MySuperObject :) var js = document.createElement("script"); js.type = "text/javascript"; js.src = jsFilePath; document.body.appendChild(js); var s = new MySuperObject(); Error : MySuperObject is undefined Then you reload the page hitting F5 .(然后,您按F5重新加载页面。) And it works!(而且有效!) Confusing...(令人困惑...) So what to do about it ?</i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...