我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?
当前回答
这就是简单的:
var js = document.createElement("script");
js.type = "text/javascript";
js.src = jsFilePath;
document.body.appendChild(js);
其他回答
是的,有......
在 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
我的总体解决方案来自EdgeS的effect.js.st图书馆(我写的)。
无情的插件警报 - 我在其他 stackexchange 网络网站上. 这是一个链接到 https://codereview.stackexchange.com/questions/263764/dynamic-load-css-or-script。
您将使用什么代码或设计来支持CSS和脚本的动态加载?
要求
支持承诺-等待-async 包括错误操作支持负载一次加密,包括重新加载支持负载在头部,身体,或当前的脚本元素支持负载 css,js,mjs 模块或其他脚本类型的支持其他标签特,如 nonce,crossorigin 等
static loadScriptOrStyle(url, options) {
// provenance :<# **Smallscript EdgeS efekt** `efekt.js.st` github libraries #>
// returns :<Promise#onload;onerror>
// options :<# `fIgnoreCache`, `fAppendToHead`, `fUrlIsStyle`, `attrs:{}` #>
const head = document.head; let node = options?.fAppendToBody ? document.body : head;
const url_loader_cache = document.head.url_loader_cache
? head.url_loader_cache
: (head.url_loader_cache = {script:{},link:{}})
const kind = (options?.fUrlIsStyle || /\.css(?:(?:\?|#).*)?$/i.test(url))
? 'link' : 'script';
// check already-loaded cache
if(url_loader_cache[kind][url]) {
const el = url_loader_cache[kind][url];
// support `fIgnoreCache` reload-option; should not use on `head`
if(options?.fIgnoreCache)
el.remove();
else
return(new CustomEvent('cache',{detail:el}));
}
// (re)create and record it
const self = document.currentScript;
const el = url_loader_cache[kind][url] = document.createElement(kind);
const append = (!self || options?.fAppendToHead || options?.fAppendToBody)
? el => node.appendChild(el)
: el => self.parentNode.insertBefore(el, self);
const load = new Promise((resolve, reject) => {
el.onload = e => {e.detail = el;resolve(e)};
el.onerror = e => {e.detail = el;reject(e)};
// `onload` or `onerror` possibly alter `cache` value
// throw(new URIError(`The ${url} didn't load correctly.`))
});
// configure `module` attr, as appropriate
if(/\.mjs(?:(?:\?|#).*)?$/i.test(url))
el.type = 'module'
// configure other attrs as appropriate (referrer, nonce, etc)
for(const key in options?.attrs) {el[key] = attrs[key]}
// trigger it
if(kind === 'link') el.rel = 'stylesheet', el.href = url; else el.src = url;
append(el);
return(load);
}
您也可以使用 gulp, gulp-concat, gulp-typescript with /// <reference path= 包括:
{
"scripts": {
"gulp": "gulp main"
},
"dependencies": {
"@types/gulp": "^4.0.6",
"@types/gulp-concat",
"@types/gulp-typescript",
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-resolve-dependencies": "^3.0.1",
"gulp-typescript": "^6.0.0-alpha.1",
"typescript": "^3.7.3"
}
}
文件 src/someimport.ts
class SomeClass {
delay: number;
}
/// <reference path="./someimport.ts" />
someclass = new SomeClass();
someclass.delay = 1;
var gulp = require("gulp");
var concat = require('gulp-concat');
var resolveDependencies = require('gulp-resolve-dependencies');
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
gulp.task("main", function() {
return gulp
.src(["src/main.ts"])
.pipe(resolveDependencies({
pattern: /^\s*\/\/\/\s*<\s*reference\s*path\s*=\s*(?:"|')([^'"\n]+)/gm
}))
.on('error', function(err) {
console.log(err.message);
})
.pipe(tsProject())
.pipe(concat('main.js'))
.pipe(gulp.dest("build/"));
});
如果您想针对所有 TypeScript 项目文件而不是仅是 src/main.ts,您可以取代以下文件:
return gulp
.src(["src/main.ts"])
.pipe(resolveDependencies({
...
// -->
return tsProject
.src()
.pipe(resolveDependencies({
...
如果您不想使用 TypeScript,您可以使用此简化 gulpfile.js 并从 package.json 中删除所有包含的 TypeScript:
圖片來源:Gulpfile.js
var gulp = require("gulp");
var concat = require('gulp-concat');
var resolveDependencies = require('gulp-resolve-dependencies');
gulp.task("main", function() {
return gulp
.src(["src/main.js"])
.pipe(resolveDependencies({
pattern: /^\s*\/\/\/\s*<\s*reference\s*path\s*=\s*(?:"|')([^'"\n]+)/gm
}))
.on('error', function(err) {
console.log(err.message);
})
.pipe(concat('main.js'))
.pipe(gulp.dest("build/"));
});
{
"scripts": {
"gulp": "gulp main"
},
"dependencies": {
"gulp": "^4.0.2",
"gulp-concat": "^2.6.1",
"gulp-resolve-dependencies": "^3.0.1"
}
}
class SomeClass {
}
/// <reference path="./someimport.ts" />
someclass = new SomeClass();
someclass.delay = 1;
<html>
<head>
<script src="main.js"></script>
</head>
<body>
<script type="text/javascript">
console.log(someclass.delay);
</script>
</body>
</html>
TypeScript: Gulp 我可以使用 TypeScript 没有 RequireJS? 需要使用 Node.js 上的 Gulp.js 客户端使用另一个 JavaScript 文件的主要文件的简单折叠: 没有折叠的参考错误: 需要没有定义 如何使用 Gulp.js 编写 TypeScript 浏览器 Node.js 模块? 使用 babel 使用文件的折叠 如何在浏览器中“要求” CommonJS 模块? 有没有替代的浏览器
若要在 JavaScript 中输入另一个脚本,请使用输入关键字:
import '/src/js/example.js';
// both types of quotes work
import "/src/js/example2.js";
另一种方式,在我看来是更清洁的,是做一个同步的Ajax请求而不是使用一个<script>标签。
下面是使用 jQuery 的例子:
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();