prefetch-polyfill-webpack-plugin

0.2.0 • Public • Published

prefetch-polyfill-webpack-plugin

Build Status Coverage Status npm package npm downloads License: MIT

Intro

This plugin automatically wire up your async thunks with a prefetch polyfill function(using new Image().src or <script async>) for platform which doesn't support <link rel='prefetch'>, such as safari, to improve load time.

This is an extension plugin for html-webpack-plugin.

The prefetch polyfill function will be injected before </body>.

<!-- as default it use new Image().src -->
<script>
  (function(){
    var ua = (typeof navigator !== 'undefined' ? navigator.userAgent || '' : '')
    if(/safari|iphone|ipad|ipod|msie|trident/i.test(ua) && !/chrome|crios|crmo|firefox|iceweasel|fxios|edge/i.test(ua)) {
      window.onload = function () {
        var i = 0, length = 0,
          preloadJs = ['/chunk.a839f9eac501a92482ca.js', ...your thunks]
 
        for (= 0, length = preloadJs.length; i < length; i++) {
          new Image().src = preloadJs[i]
        }
      }
    }
  })()
</script> 
 
<!-- you can choose to use <script async> -->
<script>
(function(){
  var ua = (typeof navigator !== 'undefined' ? navigator.userAgent || '' : '')
  if(/safari|iphone|ipad|ipod|msie|trident/i.test(ua) && !/chrome|crios|crmo|firefox|iceweasel|fxios|edge/i.test(ua)) {
    window.onload = function () {
      var i = 0, length = 0, js,
        preloadJs = ['/chunk.a839f9eac501a92482ca.js', ...your thunks]
 
      for (= 0, length = preloadJs.length; i < length; i++) {
        js = document.createElement('script')
        js.src = preloadJs[i]
        js.async = true
        document.body.appendChild(js)
      }
    }
  }
})()
</script> 

example

Install

npm install prefetch-polyfill-webpack-plugin --save-dev

Usage

In webpack config, require the plugin:

const PrefetchPolyfillPlugin = require('prefetch-polyfill-webpack-plugin');

and add this plugin after HtmlWebpackPlugin:

plugins: [
  new HtmlWebpackPlugin(),
  new PrefetchPolyfillPlugin()
]

This plugin works well with preload-webpack-plugin. If you are using code splitting you are recommended to use both plugin at the same time.

options

mode

Set mode to async to use <script async> to prefetch, or use new Image().src as default.

plugins: [
  new HtmlWebpackPlugin(),
  new PrefetchPolyfillPlugin({
    mode: 'async'
  })
]

Acknowledgment

preload-webpack-plugin

LICENSE

MIT

Readme

Keywords

none

Package Sidebar

Install

npm i prefetch-polyfill-webpack-plugin

Weekly Downloads

6

Version

0.2.0

License

MIT

Last publish

Collaborators

  • jin5354