如何在另一个JavaScript文件中包含JavaScript文件?
JavaScript中是否有类似于CSS中的如何在另一个JavaScript文件中包含JavaScript文件?,javascript,file,import,include,Javascript,File,Import,Include,JavaScript中是否有类似于CSS中的@import的东西,允许您在另一个JavaScript文件中包含一个JavaScript文件?可以动态生成JavaScript标记,并从其他JavaScript代码中将其附加到HTML文档中。这将加载目标JavaScript文件 function includeJs(jsFilePath) { var js = document.createElement("script"); js.type = "text/javascript"
@import
的东西,允许您在另一个JavaScript文件中包含一个JavaScript文件?可以动态生成JavaScript标记,并从其他JavaScript代码中将其附加到HTML文档中。这将加载目标JavaScript文件
function includeJs(jsFilePath) {
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
}
includeJs("/path/to/some/file.js");
也许你可以使用我在本页找到的这个函数:
JavaScript的旧版本没有导入、包含或要求,因此开发了许多不同的方法来解决这个问题 但自2015年(ES6)以来,JavaScript已经有了在Node.js中导入模块的标准,而Node.js也支持JavaScript 为了与旧浏览器兼容,可以使用和/或透明工具等构建工具 ES6模块 ECMAScript(ES6)模块从v8.5开始就有了
--experimental modules
标志,至少从Node.js v13.8.0开始就没有这个标志。要启用“ESM”(与Node.js以前的CommonJS样式模块系统[“CJS”]),您可以在package.json
中使用“type”:“module”
,或者为文件提供扩展名.mjs
。(类似地,如果默认为ESM,则使用Node.js以前的CJS模块编写的模块可以命名为.CJS
)
使用package.json
:
{
“类型”:“模块”
}
然后module.js
:
import { hello } from './module.js';
let val = hello(); // val is "Hello";
export function hello() {
return "Hello";
}
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
导出函数hello(){
回复“你好”;
}
然后main.js
:
import { hello } from './module.js';
let val = hello(); // val is "Hello";
export function hello() {
return "Hello";
}
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
使用.mjs
,您将拥有模块.mjs
:
import { hello } from './module.js';
let val = hello(); // val is "Hello";
export function hello() {
return "Hello";
}
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
然后main.mjs
:
import { hello } from './module.js';
let val = hello(); // val is "Hello";
export function hello() {
return "Hello";
}
import { hello } from './module.mjs';
let val = hello(); // val is "Hello";
浏览器中的ECMAScript模块
浏览器支持直接加载ECMAScript模块(无需Webpack等工具)、Safari 10.1、Chrome 61、Firefox 60和Edge 16。在上检查当前支持。无需使用Node.js'.mjs
扩展;浏览器完全忽略模块/脚本上的文件扩展名
从“./hello.mjs”导入{hello};//也可以是简单的“hello.js”`
你好(“世界”);
//hello.mjs——也可以是简单的“hello.js”`
导出函数hello(文本){
const div=document.createElement('div');
div.textContent=`Hello${text}`;
文件.正文.附件(div);
}
阅读更多
浏览器中的动态导入
动态导入允许脚本根据需要加载其他脚本:
导入('hello.mjs')。然后(模块=>{
module.hello(“世界”);
});
阅读更多
Node.js需要
在Node.js中仍然广泛使用的较旧的CJS模块样式是系统
//mymodule.js
module.exports={
您好:函数(){
回复“你好”;
}
}
//server.js
常量myModule=require('./myModule');
让val=myModule.hello();//瓦尔说“你好”
JavaScript还有其他方法可以在不需要预处理的浏览器中包含外部JavaScript内容
AJAX加载
您可以通过AJAX调用加载其他脚本,然后使用eval
运行它。这是最简单的方法,但由于JavaScript沙盒安全模型,它仅限于您的域。使用eval
也会打开漏洞、黑客和安全问题的大门
提取装载
与动态导入一样,您可以通过fetch
调用加载一个或多个脚本,使用库控制脚本依赖项的执行顺序:
jQuery加载
该库提供加载功能:
$.getScript(“my_lovely_script.js”,function()){
警报(“已加载脚本,但不一定执行”);
});
动态脚本加载
您可以将带有脚本URL的脚本标记添加到HTML中。为了避免jQuery的开销,这是一个理想的解决方案
脚本甚至可以驻留在不同的服务器上。此外,浏览器还会评估代码。
标记可以插入网页
,也可以在关闭
标记之前插入
下面是一个如何工作的示例:
函数dynamicallyLoadScript(url){
var script=document.createElement(“脚本”);//创建脚本DOM节点
script.src=url;//将其src设置为提供的url
document.head.appendChild(script);//将其添加到页面的head部分末尾(可以将“head”更改为“body”以将其添加到body部分末尾)
}
此函数将在页面标题部分的末尾添加一个新的
标记,其中src
属性设置为作为第一个参数提供给函数的URL
中讨论并说明了这两种解决方案
检测脚本何时执行
现在,有一个大问题你必须知道。这样做意味着您可以远程加载代码。现代web浏览器将加载文件并继续执行当前脚本,因为它们异步加载所有内容以提高性能。(这适用于jQuery方法和手动动态脚本加载方法。)
这意味着如果您直接使用这些技巧,您将无法在请求加载代码后的下一行使用新加载的代码,因为它仍在加载
例如:my\u lovely\u script.js
包含MySuperObject
:
var js=document.createElement(“脚本”);
js.type=“text/javascript”;
js.src=jsFilePath;
document.body.appendChild(js);
var s=新的MySuperObject();
错误:MySuperObject未定义
然后按F5重新加载页面。而且它有效!迷惑
那怎么办呢?
好吧,你可以使用作者在我给你的链接中建议的黑客。总之,对于匆忙的人,他使用事件在加载脚本时运行回调函数。因此,您可以使用远程库将所有代码放入回调函数中。例如:
function require(script) {
$.ajax({
url: script,
dataType: "script",
async: false, // <-- This is the key
success: function () {
// all good...
},
error: function () {
throw new Error("Could not load script " + script);
}
});
}
require("/scripts/subscript.js");
subscript.doSomethingCool();
/**
* @fileoverview This file stores global functions that are required by other libraries.
*/
if (typeof(jQuery) === 'undefined') {
throw 'jQuery is required.';
}
/** Defines the base script directory that all .js files are assumed to be organized under. */
var BASE_DIR = 'js/';
/**
* Loads the specified file, outputting it to the <head> HTMLElement.
*
* This method mimics the use of using in C# or import in Java, allowing
* JavaScript files to "load" other JavaScript files that they depend on
* using a familiar syntax.
*
* This method assumes all scripts are under a directory at the root and will
* append the .js file extension automatically.
*
* @param {string} file A file path to load using C#/Java "dot" syntax.
*
* Example Usage:
* imports('core.utils.extensions');
* This will output: <script type="text/javascript" src="/js/core/utils/extensions.js"></script>
*/
function imports(file) {
var fileName = file.substr(file.lastIndexOf('.') + 1, file.length);
// Convert PascalCase name to underscore_separated_name
var regex = new RegExp(/([A-Z])/g);
if (regex.test(fileName)) {
var separated = fileName.replace(regex, ",$1").replace(',', '');
fileName = separated.replace(/[,]/g, '_');
}
// Remove the original JavaScript file name to replace with underscore version
file = file.substr(0, file.lastIndexOf('.'));
// Convert the dot syntax to directory syntax to actually load the file
if (file.indexOf('.') > 0) {
file = file.replace(/[.]/g, '/');
}
var src = BASE_DIR + file + '/' + fileName.toLowerCase() + '.js';
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
$('head').find('script:last').append(script);
}
define(['lib/dependency1', 'lib/dependency2'], function (d1, d2) {
//Your actual script goes here.
//The dependent scripts will be fetched if necessary.
return libraryObject; //For example, jQuery object
});
require(['some-dependency'], function(dependency) {
//Your script goes here
//some-dependency.js is fetched.
//Then your script is executed
});
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
xhr = new XMLHttpRequest();
xhr.open("GET", "/soap/ajax/11.0/connection.js", false);
xhr.send();
eval(xhr.responseText);
// ----- USAGE -----
require('ivar.util.string');
require('ivar.net.*');
require('ivar/util/array.js');
require('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
ready(function(){
//Do something when required scripts are loaded
});
//--------------------
var _rmod = _rmod || {}; //Require module namespace
_rmod.LOADED = false;
_rmod.on_ready_fn_stack = [];
_rmod.libpath = '';
_rmod.imported = {};
_rmod.loading = {
scripts: {},
length: 0
};
_rmod.findScriptPath = function(script_name) {
var script_elems = document.getElementsByTagName('script');
for (var i = 0; i < script_elems.length; i++) {
if (script_elems[i].src.endsWith(script_name)) {
var href = window.location.href;
href = href.substring(0, href.lastIndexOf('/'));
var url = script_elems[i].src.substring(0, script_elems[i].length - script_name.length);
return url.substring(href.length+1, url.length);
}
}
return '';
};
_rmod.libpath = _rmod.findScriptPath('script.js'); //Path of your main script used to mark
//the root directory of your library, any library.
_rmod.injectScript = function(script_name, uri, callback, prepare) {
if(!prepare)
prepare(script_name, uri);
var script_elem = document.createElement('script');
script_elem.type = 'text/javascript';
script_elem.title = script_name;
script_elem.src = uri;
script_elem.async = true;
script_elem.defer = false;
if(!callback)
script_elem.onload = function() {
callback(script_name, uri);
};
document.getElementsByTagName('head')[0].appendChild(script_elem);
};
_rmod.requirePrepare = function(script_name, uri) {
_rmod.loading.scripts[script_name] = uri;
_rmod.loading.length++;
};
_rmod.requireCallback = function(script_name, uri) {
_rmod.loading.length--;
delete _rmod.loading.scripts[script_name];
_rmod.imported[script_name] = uri;
if(_rmod.loading.length == 0)
_rmod.onReady();
};
_rmod.onReady = function() {
if (!_rmod.LOADED) {
for (var i = 0; i < _rmod.on_ready_fn_stack.length; i++){
_rmod.on_ready_fn_stack[i]();
});
_rmod.LOADED = true;
}
};
_.rmod = namespaceToUri = function(script_name, url) {
var np = script_name.split('.');
if (np.getLast() === '*') {
np.pop();
np.push('_all');
}
if(!url)
url = '';
script_name = np.join('.');
return url + np.join('/')+'.js';
};
//You can rename based on your liking. I chose require, but it
//can be called include or anything else that is easy for you
//to remember or write, except "import", because it is reserved
//for future use.
var require = function(script_name) {
var uri = '';
if (script_name.indexOf('/') > -1) {
uri = script_name;
var lastSlash = uri.lastIndexOf('/');
script_name = uri.substring(lastSlash+1, uri.length);
}
else {
uri = _rmod.namespaceToUri(script_name, ivar._private.libpath);
}
if (!_rmod.loading.scripts.hasOwnProperty(script_name)
&& !_rmod.imported.hasOwnProperty(script_name)) {
_rmod.injectScript(script_name, uri,
_rmod.requireCallback,
_rmod.requirePrepare);
}
};
var ready = function(fn) {
_rmod.on_ready_fn_stack.push(fn);
};
var require = function (src, cb) {
cb = cb || function () {};
var newScriptTag = document.createElement('script'),
firstScriptTag = document.getElementsByTagName('script')[0];
newScriptTag.src = src;
newScriptTag.async = true;
newScriptTag.onload = newScriptTag.onreadystatechange = function () {
(!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') && (cb());
};
firstScriptTag.parentNode.insertBefore(newScriptTag, firstScriptTag);
}
var foo = $import("./Form/Input/Tel");
function() {
return {
prop: "",
method: function(){}
}
}
node jsic.js src/main.js build/mail.js
var foo = function() {
return {
prop: "",
method: function(){}
}
};
(function () {
var li = document.createElement('script');
li.type = 'text/javascript';
li.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
li.async = true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(li, s);
})();
document.write('<script src="myscript.js" type="text/javascript"></script>');
$.getScript("another_script.js");
function myRequire( url ) {
var ajax = new XMLHttpRequest();
ajax.open( 'GET', url, false ); // <-- the 'false' makes it synchronous
ajax.onreadystatechange = function () {
var script = ajax.response || ajax.responseText;
if (ajax.readyState === 4) {
switch( ajax.status) {
case 200:
eval.apply( window, [script] );
console.log("script loaded: ", url);
break;
default:
console.log("ERROR: script not loaded: ", url);
}
}
};
ajax.send(null);
}
// scripts-global.mix.js
// Plugins - Global
@import "global-plugins/headroom.js";
@import "global-plugins/retina-1.1.0.js";
@import "global-plugins/isotope.js";
@import "global-plugins/jquery.fitvids.js";
import name from "module-name";
import { member } from "module-name";
import { member as alias } from "module-name";
import { member1 , member2 } from "module-name";
import { member1 , member2 as alias2 , [...] } from "module-name";
import name , { member [ , [...] ] } from "module-name";
import "module-name" as name;
<html>
<body onload="bodyReady();" >
<script src="myvariables.js" > </script>
<script src="main.js" > </script>
<!-- Some other code -->
</body>
</html>
var myVar1 = "I am variable from myvariables.js";
// ...
function bodyReady() {
// ...
alert (myVar1); // This shows "I am variable from myvariables.js", which I needed
// ...
}
// ...
A = {};
A.func1 = function() {
console.log("func1");
}
A.func2 = function() {
console.log("func2");
}
A.func1();
A.func2();
<head>
<script type="text/javascript" src="global.js"></script>
<script type="text/javascript" src="file1.js"></script>
<script type="text/javascript" src="file2.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
function loadJs( url ){
return new Promise(( resolve, reject ) => {
if (document.querySelector( `head > script[ src = "${url}" ]`) !== null ){
console.warn( `script already loaded: ${url}` );
resolve();
}
const script = document.createElement( "script" );
script.src = url;
script.onload = resolve;
script.onerror = function( reason ){
// This can be useful for your error-handling code
reason.message = `error trying to load script ${url}`;
reject( reason );
};
document.head.appendChild( script );
});
}
try { await loadJs("https://.../script.js"); }
catch(error) { console.log(error); }
await loadJs( "https://.../script.js" ).catch( err => {} );
loadJs( "https://.../script.js" ).then( res => {} ).catch( err => {} );
<!DOCTYPE HTML>
<html>
<head>
<script src="script1.js"></script>
<script src="script2.js"></script>
</head>
<body></body>
</html>
// main.js file
export function add (a, b) {
return a + b;
}
export default function multiply (a, b) {
return a * b;
}
// test.js file
import {add}, multiply from './main'; // For named exports between curly braces {export1, export2}
// For default exports without {}
console.log(multiply(2, 2)); // logs 4
console.log(add(1, 2)); // logs 3
// main.js file
function add (a, b) {
return a + b;
}
module.exports = add; // Here we add our 'add' function to the exports object
// test.js file
const add = require('./main');
console.log(add(1,2)); // logs 3
<script type="module" src="script.js"></script>
import { hello } from './module.js';
...
// alert(hello());
export function hello() {
return "Hello World";
}