styletools/async 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

styletools/async

Composer 安装命令:

composer create-project styletools/async

包简介

A lightweight and high performance async CSS and script loader for frontend optimization.

README 文档

README

Build Status Version npm version Latest Stable Version

$async Async CSS and Script Loader

A lightweight and high performance async CSS and script loader with state of the art features for frontend optimization (FEO).

Install via npm

npm install @style.tools/async --save

Install via PHP Composer

composer require styletools/async

Examples

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

$async can be controlled from a HTML attribute which enables strict security.

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

The JSON configuration can be compressed to save size in the HTML (online compressor).

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

Documentation

Documentation is available on docs.style.tools/async.

Description

$async is designed as the ultimate CSS and script loader for modern frontend optimization (FEO). It provides state of the art features, the absolute best performance and the tiniest HTML footprint. $async supports all browsers including IE9+.

  • 100% JSON control.
  • Google Closure Compiler (GCC) with Advanced mode script compression (reliable and performant in all browsers).

Modular

$async is modular and easy to use: select only the features that are needed to achieve the tiniest script size.

  • simply stitch pre-optimized GCC modules together for a performant IIFE. You can wrap the modules in dist/ into an IIFE, e.g. !function(){/* stitched modules */}();. Follow the module order in package.json.
  • Online IIFE generator (adds an extra GCC Advanced mode compression layer)
  • Node.js/CLI IIFE generator (adds an extra GCC Advanced mode compression layer)
  • PHP IIFE generator (available on request: info@style.tools)

Chainable

$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');

Security

$async supports a strict Content-Security-Policy (CSP) and SRI security by using a HTML attribute on the script element. The data-c attribute accepts JSON config.

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

Advanced download and exec/render timing

$async provides advanced loading and timing techniques.

  • control the insert target.
  • time the download and/or exec/render using methods such as requestAnimationFrame, requestIdleCallback and $lazy (Intersection Observer).
  • dependency based loading.
  • responsive Media Query based loading with cross-browser support for viewport changes.
  • just-in-time loading using a custom javascript method.
$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 */ });

just-in-time loading

$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's

$async provides API's for access to the dependency resolver and timing methods.

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

$async enables to load stylesheets and script from localStorage or Cache API cache which is much faster than browser cache.

For a demo, see 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 compression

$async provides a JSON compression technique to minimize the size of configuration.

Online compressor | 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 script-injected stylesheet/script capture

$async provides an innovation to capture and rewrite, remove or modify/optimize script-injected stylesheets and scripts. The solution supports both native DOM insert method rewriting and MutationObserver.

  • rewrite
  • remove
  • modify
  • optimize (code optimization, apply timing, responsive loading, dependencies etc.)
// 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
   }
);

Performance API timings for loading performance optimization

$async provides a debug mode with advanced Performance API timings that enables to analyse and optimize the CSS and script loading performance.

$async demo

Demo

$async is in use on www.e-scooter.co (demo website) and css-art.com (test environment).

styletools/async 适用场景与选型建议

styletools/async 是一款 基于 JavaScript 开发的 Composer 扩展包,目前已累计 48 次下载、GitHub Stars 达 19, 最近一次更新时间为 2019 年 05 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「css」 「optimization」 「asynchronous」 「localstorage」 「async-css」 「css-loader」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 styletools/async 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 styletools/async 我们能提供哪些服务?
定制开发 / 二次开发

基于 styletools/async 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 48
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 19
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 19
  • Watchers: 1
  • Forks: 3
  • 开发语言: JavaScript

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-05-18