JavaScript中是否有类似于CSS中@import的内容,可让您在另一个JavaScript文件中包含一个JavaScript文件?
@import
The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.(JavaScript的旧版本没有导入,包含或要求,因此已经开发了许多解决此问题的方法。)
--experimental-modules
.mjs
// module.mjs export function hello() { return "Hello"; }
// main.mjs import { hello } from 'module'; // or './module' let val = hello(); // val is "Hello";
<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); }
<script type="module"> import('hello.mjs').then(module => { module.hello('world'); }); </script>
// mymodule.js module.exports = { hello: function() { return "Hello"; } }
// server.js const myModule = require('./mymodule'); let val = myModule.hello(); // val is "Hello"
eval
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)}`) })
$.getScript("my_lovely_script.js", function() { alert("Script loaded but not necessarily executed."); });
<script>
<head>
</body>
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) }
src
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
1.4m articles
1.4m replys
5 comments
57.0k users