我如何在另一个JavaScript文件中添加一个JavaScript文件,类似于CSS中的 @import?


当前回答

我的总体解决方案来自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);
}

其他回答

雖然這些答案很棒,但有一個簡單的「解決方案」已經存在,因為脚本充電存在,它將覆蓋大多數人使用案例的99.999%。

<!DOCTYPE HTML>
<html>
    <head>
        <script src="script1.js"></script>
        <script src="script2.js"></script>
    </head>
    <body></body>
</html>

如果脚本2需要脚本1,这实际上是做这样的事情的绝对最简单的方式,我很惊讶,没有人带来了这一点,因为这是最明显和最简单的答案,几乎每个案例都会适用。

这应该做:

xhr = new XMLHttpRequest();
xhr.open("GET", "/soap/ajax/11.0/connection.js", false);
xhr.send();
eval(xhr.responseText);

另一个方法是使用HTML进口,这些可以包含脚本参考以及风格表参考。

您可以将 HTML 文件链接到

<link rel="import" href="vendorScripts.html"/>

在 vendorScripts.html 文件中,您可以包含您的脚本参考,如:

<script src="scripts/vendors/jquery.js"></script>
<script src="scripts/vendors/bootstrap.js"></script>
<script src="scripts/vendors/angular.js"></script>
<script src="scripts/vendors/angular-route.js"></script>

查看 HTML Imports 更多详细信息。

不幸的是,它只在Chrome中工作。

这就是简单的:

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

在JavaScript中实施模块有几种方式,这里有两个最受欢迎的方式:

ES6 模块

浏览器还不支持这个模块化系统,所以为了你使用这个合成,你必须使用一个包装,如Webpack. 使用一个包装是更好的,因为这可以将所有的不同的文件融入一个单一(或一对相关的)文件。

// 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

CommonJS(在 Node.js 中使用)

这个模块化系统在 Node.js 中使用,你基本上将你的出口添加到一个被称为 module.exports 的对象,然后你可以通过一个要求(‘modulePath’)访问这个对象。

// 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