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


当前回答

请注意,我们通常使用静态脚本,所以我们希望尽可能多地从缓存中获取。

这节省了网络流量,加速着陆。

使用

$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
  console.log( textStatus );
});

存储:真实的选项已添加到 Ajax 方法。

其他回答

使用 ES6 的进口和出口模块与 Node.js 合作

使用.mjs 扩展而不是.js 的名称文件

创建文件

touch main.mjs lib.mjs

主.js

import { add } from './lib.mjs';
console.log(add(40, 2));

英格兰MJ

export let add = (x,y) => {
  return x + y
}

跑步

node --experimental-modules main.js

下面是使用HTML导入的浏览器(而不是Node.js)。

首先,所有 JavaScript 类和脚本都不是.js 文件,而是.js.html 文件(.js.html 只是在 HTML 页面和完整的 JavaScript 脚本/类之间识别),在 <script> 标签中,如下:

MyClass.js.html 的内容:

<script>
   class MyClass {

      // Your code here..

   }

</script>

然后,如果你想进口你的班级,你只需要使用HTML进口:

<link rel="import" href="relative/path/to/MyClass.js.html"/>

<script>
   var myClass = new MyClass();
   // Your code here..
</script>

此分類上一篇: HTML 輸入將減少

HTML 进口减少,有利于 ES6 模块,您应该使用 ES6 模块。

可以动态地创建一个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");

如果您使用 Angular,那么一个插件模块 $ocLazyLoad 可以帮助您做到这一点。

以下是其文档的一些引用:

加载一个或多个模块和组件有多个文件: $ocLazyLoad.load([‘testModule.js’,‘testModuleCtrl.js’,‘testModuleService.js’]);加载一个或多个模块有多个文件,并在需要时指定一个类型: 注意: 使用需要JS 风格格格格式(例如,从 js! 开始时),不要指定一个文件扩展。

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