styletools/async

一个轻量级且高性能的异步 CSS 和脚本加载器,用于前端优化。

安装: 47

依赖: 0

建议者: 0

安全性: 0

星标: 19

关注者: 2

分支: 3

开放问题: 0

语言:JavaScript

类型:项目

2.0.4 2021-12-03 12:15 UTC

This package is auto-updated.

Last update: 2024-09-06 12:41:36 UTC


README

Build Status Version npm version Latest Stable Version

$async 异步 CSS 和脚本加载器

一个轻量级且高性能的异步 CSS 和脚本加载器,具有最先进的功能,用于前端优化(FEO)。

通过 npm 安装

npm install @style.tools/async --save

通过 PHP Composer 安装

composer require styletools/async

示例

$async([
   'sheet.css',
   'script.js'
]).then(function() { /* ready */ });

$async 可以通过 HTML 属性进行控制,从而实现严格的安全。

<!-- config via an HTML attribute -->
<script async src="js/async-iife.js" data-c='[
   [
      "css/sheet1.css",
      "js/script.js",
      {
         "href": "https://cdn.com/css/sheet2.css",
         "attributes": {
            "integrity": "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC",
            "crossorigin": "anonymous"
         }
      },
      {
         "src": "https://cdn.com/js/script2.js",
         "attributes": {
            "integrity": "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC",
            "crossorigin": "anonymous"
         },
         "load_timing": "domReady",
         "ref": "x"
      },
      {
         "src": "js/script3.js",
         "dependencies": "x"
      }
   ],
   {
      "render_timing": "requestAnimationFrame",
      "exec_timing": {
         "type": "requestIdleCallback",
         "timeout": 1000
      }
   }
]'></script>

JSON 配置可以压缩以节省 HTML 的大小(在线压缩器)。

<script async src="js/async-iife.js" data-c='[["css/sheet1.css","js/script.js",{"4":"https://cdn.com/css/sheet2.css","14":{"integrity":"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC","crossorigin":"anonymous"}},{"5":"https://cdn.com/js/script2.js","14":{"integrity":"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC","crossorigin":"anonymous"},"16":"x","48":54},{"5":"js/script3.js","15":"x"}],{"49":52,"60":{"2":53,"57":1000}}]'></script>

文档

文档可在 docs.style.tools/async 上找到。

描述

$async 设计为现代前端优化(FEO)的终极 CSS 和脚本加载器。它提供最先进的功能,最佳性能和最小的 HTML 脚印。$async 支持包括 IE9+ 在内的所有浏览器。

  • 100% JSON 控制。
  • 带有 高级模式 脚本压缩的 Google Closure Compiler (GCC)(在所有浏览器中可靠且性能出色)。

模块化

$async 是模块化的,易于使用:只选择所需的功能以实现最小的脚本大小。

  • 简单地缝合预优化的 GCC 模块以创建高性能的 IIFE。您可以将模块包裹在 dist/ 中的 IIFE 中,例如 !function(){/* 缝合模块 */}();。请按照 package.json 中的模块顺序执行。
  • 在线 IIFE 生成器(添加额外的 GCC 高级模式 压缩层)
  • Node.js/CLI IIFE 生成器(添加额外的 GCC 高级模式 压缩层)
  • PHP IIFE 生成器(可请求提供:info@style.tools

链式调用

$async
   .on('load',function(sheet, sheetEl){
      //  sheet.css or other-sheet.css loaded
   }) 
   .on('sheet-ref',function() { }) // sheet with ref-name loaded
   .on('sheet.css', function() {}); // sheet with href loaded
   .load({
      href: 'sheet.css', 
      ref: 'sheet-ref'
   })
   .then(function() { }) // sheet.css loaded
   .load('other-sheet.css');

安全性

$async 通过使用脚本元素的 HTML 属性支持严格的内容安全策略(CSP)和 SRI 安全性。data-c 属性接受 JSON 配置。

<script async src="js/async.js" data-c='[
   [
      "css/sheet1.css",
      {
         "href": "https://cdn.com/css/sheet2.css",
         "attributes": {
            "integrity": "sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC",
            "crossorigin": "anonymous"
         }
      }
   ]
]'></script>

高级下载和执行/渲染时间

$async 提供了高级的加载和定时技术。

  • 控制插入目标。
  • 使用 requestAnimationFramerequestIdleCallback$lazy(Intersection Observer)等方法计时下载和/或执行/渲染。
  • 基于依赖的加载。
  • 基于响应式 Media Query 的加载,具有跨浏览器对视口更改的支持。
  • 使用自定义 JavaScript 方法进行 即时 加载。
$async(
   [
      "sheet.css",
      {
         href:"other-sheet.css",
         dependencies: ["sheet.css"], // wait for sheet.css via dependencies
         load_timing: {
            type: "lazy", // use $lazy for timing (Intersection Observer)
            config: [".selector-in-view", 0, "200px"], // visible within 200 pixels
         },
         ref: "other"
      }, 
      {
         href:"mobile-sheet.css",
         dependencies: "other", // dependency by ref
         target: {
            after: "meta[charset]" // control insert target
         },
         load_timing: {
            type: "media", // download stylesheet based on a media query (works with viewport changes, e.g. viewport rotate)
            media: "screen and (max-width: 600px)"
         }
      },
      {
         inline: "inline_script_with_timing_and_dependency();",
         ref: "inline-code"
      },
      {
         src: "script.js",
         exec_timing: "requestIdleCallback",
         dependencies: "inline-code"
      }
   ],
   /* global options: applied to all stylesheets */
   {
      // base directory for relative sheet URLs
      base: "/long/path/to/css/",

      // render timing: paint sheet with requestAnimationFrame
      render_timing: "requestAnimationFrame"
   } 
)
.then(function() { /* ready */ });

即时加载

$async(
   {
      href:"popup-css.css",
      load_timing: {
         type: "method", // trigger download using custom javascript method
         method: "load_popup_css"
      }
   },{
      src:"popup-script.js",
      load_timing: {
         type: "method",
         method: "load_popup_js"
      }
   }
);

// just-in-time loading
jQuery('button.popup').on('click', function() {

   // user clicks a button
   // load popup script/css just-in-time

    load_popup_css().then(function() {
      alert('popup CSS loaded');
    });

    load_popup_js().then(function() {
      alert('popup script loaded');
    });
});

API

$async 提供了 API,用于访问依赖解析器和定时方法。

// dependency resolver
$async.dependencies(['name'], function() { /* dependency loaded */ });

// timing method
$async.time("requestAnimationFrame", function() { /* callback */ });
$async.time(48, function() {}); // the same using the JSON compression index key for 'requestAnimationFrame'

localStorage 缓存

$async 允许从 localStorageCache API 缓存加载样式表和脚本,这比浏览器缓存快得多。

有关演示,请参阅 css-art.com

$async({
   href: "sheet.css",
   cache: {
      type: "localstorage",
      max_size: 10000, // cache only <10kb
      fallback: "cache-api", // fallback to Cache-API for bigger sheets
      update: {
         head: true, // use HTTP HEAD request to check for 304 - Not Modified
         interval: 86400 // update once per day
      },

      // control the source methods
      source: ["cssText","xhr","cors"], // default

      // optional: CORS proxy for retrieving the source code from external stylesheet URLs
      cors: {
         proxy: "https://cors-anywhere.herokuapp.com/", // more proxies on https://gist.github.com/jimmywarting/ac1be6ea0297c16c477e17f8fbe51347
      },

      // custom XHR config
      xhr: {
         headers: {
            "x-special-header": "secret-key" // request header to include in XHR requests
         }
      }
   }
});

JSON 压缩

$async提供了一种JSON压缩技术,以减小配置文件的大小。

在线压缩器 | Node.js/CLI

/* original config: 
{
   "href":"other-sheet.css",
   "dependencies": ["sheet.css"],
   "load_timing":{
      "type":"lazy",
      "config": [".selector-in-view",0,"200px"]
   },
   "ref":"other"
} */

// compressed
$async({"4":"other-sheet.css","15":["sheet.css"],"16":"other","48":{"2":62,"89":[".selector-in-view",0,"200px"]}});

异步脚本注入样式表/脚本捕获

$async提供了一种创新技术,用于捕获和重写、删除或修改/优化脚本注入的样式表和脚本。该解决方案支持原生的DOM插入方法重写和MutationObserver

  • 重写
  • 删除
  • 修改
  • 优化(代码优化、应用定时、响应式加载、依赖等)
// capture and remove async script-injected sheet
$async.capture(
   [
      {
         match: "bloated-sheet.css",
         action: {
            "type": "remove"
         }
      },
      {
         match: "/<script[^>]+bloated-script-id[^>]+>/",
         regex: true,
         match_type: "node",
         action: {
            "type": "remove"
         }
      },
      {
         match: "external-widget.com",
         action: {
            type: "rewrite",
            search: '/^.*cdn\.external-widget\.com/(.*).css$',
            regex: true,
            replace: "/local-nginx-proxy/$1.css",
            async: {
               "load_timing": "requestIdleCallback",
               "target": {
                  "after": "media[charset]"
               },
               "attributes": {
                  "data-cdn": "external-widget.com"
               }
            }
         }
      },
      {
         match: "customer-review.js",
         action: {
            async: { 
               "load_timing": {
                  type: 'lazy',
                  config: '#customer-review' // load script when customer review widget enters viewport
               }
            }
         }
      }
   ],
   {
      insert: true // use DOM insert method rewriting
      // observer: true // alternative: use MutationObserver
   }
);

性能API计时,用于加载性能优化

$async提供了一种带有高级性能API计时的调试模式,可以分析并优化CSS和脚本加载性能。

$async demo

演示

$async已在www.e-scooter.co(演示网站)和css-art.com(测试环境)中使用。