GithubHelp home page GithubHelp logo

vuejs / preload-webpack-plugin Goto Github PK

View Code? Open in Web Editor NEW

This project forked from googlechromelabs/preload-webpack-plugin

176.0 9.0 32.0 798 KB

A Webpack plugin for wiring up `<link rel='preload'>` (and prefetch) - supports async chunks

License: Apache License 2.0

JavaScript 100.00%

preload-webpack-plugin's Introduction

@vue/preload-webpack-plugin

NPM version

This is a fork of preload-webpack-plugin with a number of changes:

  • Uses a combination of htmlWebpackPluginBeforeHtmlProcessing and htmlWebpackPluginAlterAssetTags hooks to inject links as objects rather than strings. This allows for more flexibility when the tags need to be altered by other plugins.

  • include option can be an object in the shape of { type?, chunks?, entries? }. For example, to prefetch async chunks for a specific entry point:

    {
      rel: 'prefetch',
      include: {
        type: 'asyncChunks',
        entries: ['app']
      }
    }
  • Added an includeHtmlNames option so that the plugin is only applied to a specific HTML file.

  • Drops support for webpack v3.

  • Drops support for Node < 6.


preloads-plugin-compressor

A Webpack plugin for automatically wiring up asynchronous (and other types) of JavaScript chunks using <link rel='preload'>. This helps with lazy-loading.

Note: This is an extension plugin for html-webpack-plugin - a plugin that simplifies the creation of HTML files to serve your webpack bundles.

This plugin is a stop-gap until we add support for asynchronous chunk wiring to script-ext-html-webpack-plugin.

Introduction

Preload is a web standard aimed at improving performance and granular loading of resources. It is a declarative fetch that can tell a browser to start fetching a source because a developer knows the resource will be needed soon. Preload: What is it good for? is a recommended read if you haven't used the feature before.

In simple web apps, it's straight-forward to specify static paths to scripts you would like to preload - especially if their names or locations are unlikely to change. In more complex apps, JavaScript can be split into "chunks" (that represent routes or components) at with dynamic names. These names can include hashes, numbers and other properties that can change with each build.

For example, chunk.31132ae6680e598f8879.js.

To make it easier to wire up async chunks for lazy-loading, this plugin offers a drop-in way to wire them up using <link rel='preload'>.

Pre-requisites

This module requires Webpack 2.2.0 and above. It also requires that you're using html-webpack-plugin in your Webpack project.

Installation

First, install the package as a dependency in your package.json:

$ npm install --save-dev @vue/preload-webpack-plugin

Alternatively, using yarn:

yarn add -D @vue/preload-webpack-plugin

Usage

Next, in your Webpack config, require() the preload plugin as follows:

const PreloadWebpackPlugin = require('@vue/preload-webpack-plugin');

and finally, configure the plugin in your Webpack plugins array after HtmlWebpackPlugin:

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

When preloading files, the plugin will use different as attribute depends on the type of each file. For each file ends with .css, the plugin will preload it with as=style, for each file ends with .woff2, the plugin will preload it with as=font, while for all other files, as=script will be used.

If you do not prefer to determine as attribute depends on suffix of filename, you can also explicitly name it using as:

plugins: [
  new HtmlWebpackPlugin(),
  new PreloadWebpackPlugin({
    rel: 'preload',
    as: 'script'
  })
]

In case you need more fine-grained control of the as atribute, you could also provide a function here. When using it, entry name will be provided as the parameter, and function itself should return a string for as attribute:

plugins: [
  new HtmlWebpackPlugin(),
  new PreloadWebpackPlugin({
    rel: 'preload',
    as(entry) {
      if (/\.css$/.test(entry)) return 'style';
      if (/\.woff$/.test(entry)) return 'font';
      if (/\.png$/.test(entry)) return 'image';
      return 'script';
    }
  })
]

Notice that if as=font is used in preload, crossorigin will be added, otherwise the font resource might be double fetched. Explains can be found in this article.

By default, the plugin will assume async script chunks will be preloaded. This is the equivalent of:

plugins: [
  new HtmlWebpackPlugin(),
  new PreloadWebpackPlugin({
    rel: 'preload',
    include: 'asyncChunks'
  })
]

For a project generating two async scripts with dynamically generated names, such as chunk.31132ae6680e598f8879.js and chunk.d15e7fdfc91b34bb78c4.js, the following preloads will be injected into the document <head>:

<link rel="preload" as="script" href="chunk.31132ae6680e598f8879.js">
<link rel="preload" as="script" href="chunk.d15e7fdfc91b34bb78c4.js">

You can also configure the plugin to preload all chunks (vendor, async, normal chunks) using include: 'all', or only preload initial chunks with include: 'initial':

plugins: [
  new HtmlWebpackPlugin(),
  new PreloadWebpackPlugin({
    rel: 'preload',
    include: 'all' // or 'initial'
  })
]

In case you work with named chunks, you can explicitly specify which ones to include by passing an array:

plugins: [
  new HtmlWebpackPlugin(),
  new PreloadWebpackPlugin({
    rel: 'preload',
    include: ['home']
  })
]

will inject just this:

<link rel="preload" as="script" href="home.31132ae6680e598f8879.js">

Filtering chunks

There may be chunks that you don't want to have preloaded (sourcemaps, for example). Before preloading each chunk, this plugin checks that the file does not match any regex in the fileBlacklist option. The default value of this blacklist is [/\.map/], meaning no sourcemaps will be preloaded. You can easily override this:

new PreloadWebpackPlugin({
  fileBlacklist: [/\.whatever/]
})

Passing your own array will override the default, so if you want to continue filtering sourcemaps along with your own custom settings, you'll need to include the regex for sourcemaps:

new PreloadWebpackPlugin({
  fileBlacklist: [/\.map/, /\.whatever/]
})

Resource Hints

Should you wish to use Resource Hints (such as prefetch) instead of preload, this plugin also supports wiring those up.

Prefetch:

plugins: [
  new HtmlWebpackPlugin(),
  new PreloadWebpackPlugin({
    rel: 'prefetch'
  })
]

For the async chunks mentioned earlier, the plugin would update your HTML to the following:

<link rel="prefetch" href="chunk.31132ae6680e598f8879.js">
<link rel="prefetch" href="chunk.d15e7fdfc91b34bb78c4.js">

Demo

A demo application implementing the PRPL pattern with React that uses this plugin can be found in the demo directory.

Support

If you've found an error in this sample, please file an issue: https://github.com/googlechrome/preload-webpack-plugin/issues

Patches are encouraged, and may be submitted by forking this project and submitting a pull request through GitHub.

Contributing workflow

index.js contains the primary source for the plugin, test contains tests and demo contains demo code.

Test the plugin:

$ npm install
$ npm run test

Lint the plugin:

$ npm run lint
$ npm run lint-fix # fix linting issues

The project is written in ES2015, but does not use a build-step. This may change depending on any Node version support requests posted to the issue tracker.

Additional Notes

  • Be careful not to preload resources a user is unlikely to need. This can waste their bandwidth.
  • Use preload for the current session if you think a user is likely to visit the next page. There is no 100% guarantee preloaded items will end up in the HTTP Cache and read locally beyond this session.
  • If optimising for future sessions, use prefetch and preconnect. Prefetched resources are maintained in the HTTP Cache for at least 5 minutes (in Chrome) regardless of the resource's cachability.

Related plugins

License

Copyright 2017 Google, Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

preload-webpack-plugin's People

Contributors

addyosmani avatar asahasrabuddhe avatar atinux avatar bekos avatar conorhastings avatar dalezak avatar developit avatar githoniel avatar hanford avatar jackfranklin avatar jeffposnick avatar kuldeepkeshwar avatar laysent avatar malikshahzad228 avatar pd4d10 avatar ragingwind avatar sodatea avatar tofandel avatar toxic-johann avatar yyx990803 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

preload-webpack-plugin's Issues

Ability to disable setting crossorigin for fonts

We use webpack to build our application for electron. Our html, css and woff2 are delivered over file:// protocol. Setting crossorigin attribute on fonts results in loading the font twice.

example requests:

curl 'file:///<redacted>/Inter-Bold.3J6.woff2' \
  -H 'Origin: file://' \
  -H 'Referer: ' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Slapdash/2.6.5 Chrome/87.0.4280.141 Electron/11.3.0 Safari/537.36' \
  --compressed

curl 'file:///<redacted>/Inter-Bold.3J6.woff2' \
  -H 'Referer: ' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Slapdash/2.6.5 Chrome/87.0.4280.141 Electron/11.3.0 Safari/537.36' \
  --compressed

Please provide a way to disable it.

[Vue warn]: Cannot find element: #app

My vue.config.js:

const PreloadWebpackPlugin = require("@vue/preload-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");

module.exports = {
  publicPath: "/",
  css: {
    extract: true,
    loaderOptions: {
      scss: {
        prependData: `
          @import "~@/styles/scss/_variables_custom.scss";
          @import "~@/styles/scss/_variables.scss";
          @import "~@/styles/scss/_bootstrap_colors.scss";
        `
      }
    }
  },
  configureWebpack: {
    plugins: [
      new HtmlWebpackPlugin(),
      new PreloadWebpackPlugin({
        rel: "preload",
        as(entry) {
          if (/\.css$/.test(entry)) return "style";
          if (/\.woff$/.test(entry)) return "font";
          if (/\.png$/.test(entry)) return "image";
          return "script";
        }
      })
    ],
    module: {
      rules: [
        {
          test: /\.(pdf)(\?.*)?$/,
          use: [
            {
              loader: "url-loader",
              options: {
                name: "files/[name].[hash:8].[ext]"
              }
            }
          ]
        }
      ]
    }
  },
  pluginOptions: {
    i18n: {
      locale: "hu",
      fallbackLocale: "en",
      localeDir: "locales",
      enableInSFC: true
    }
  }
};

The app not loads and has the following error on console:

[Vue warn]: Cannot find element: #app

  warn @ vue.runtime.esm.js?2b0e:619
  query @ vue.runtime.esm.js?2b0e:5671
  Vue.$mount @ vue.runtime.esm.js?2b0e:8414
  eval @ main.ts?bc82:21
  ./src/main.ts @ app.js:2926
  webpack_require @ app.js:795
  fn @ app.js:151
  1 @ app.js:3476
  webpack_require @ app.js:795
  checkDeferredModules @ app.js:46
  (anonymous) @ app.js:976
  (anonymous) @ app.js:979

Cannot read property 'tap' of undefined

Tried to replace old preload-webpack-plugin in my webpack 5 config with this fork and I'm getting this error:

compilation PreloadPlugin[webpack-cli] TypeError: Cannot read property 'tap' of undefined
at C:\node_modules@vue\preload-webpack-plugin\src\index.js:115:65
at Hook.eval [as call] (eval at create (C:\node_modules\tapable\lib\HookCodeFactory.js:19:10), :200:1)
at Hook.CALL_DELEGATE [as _call] (C:\node_modules\tapable\lib\Hook.js:14:14)
at Compiler.newCompilation (C:\node_modules\webpack\lib\Compiler.js:993:26)
at C:\node_modules\webpack\lib\Compiler.js:1035:29
at Hook.eval [as callAsync] (eval at create (C:\node_modules\tapable\lib\HookCodeFactory.js:33:10), :20:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\node_modules\tapable\lib\Hook.js:18:14)
at Compiler.compile (C:\node_modules\webpack\lib\Compiler.js:1030:28)
at C:\node_modules\webpack\lib\Watching.js:112:19
at Hook.eval [as callAsync] (eval at create (C:\node_modules\tapable\lib\HookCodeFactory.js:33:10), :32:1)

Webpack plugin config:

plugins: [
new DefinePlugin({
"process.env": "{}"
}),
new ProgressPlugin(),
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html",
}),
new PreloadWebpackPlugin({
rel: "preload",
include: "allAssets",
fileBlacklist: [/.(js|ttf|png|eot|jpe?g|css|svg)/],
}),
],

Option to put <link/> elements at bottom of page

Issue Type: Feature Request

Description: Given the support for prefetch, it seems like it would be worthwhile to add support for media tags, and putting prefetch links down at the bottom of the index file, rather than in the head. I'm not an expert on render blocking, but it seems like putting non-critical elements outside of head (which seems to render block). Thoughts?

Preload and Prefetch config options

Hi there,

First of all, thanks for keeping up with this project.

I'm reaching you out as I'm trying to achieve prefetch and preload for different assets (e.g. I'd like to preload all the .css files but prefetch .js files).

Accordingly with some random post I could potentially use this syntax within the webpack plugins section:

new PreloadWebpackPlugin({
    rel: 'preload',
    as: 'style',
    include: 'allChunks',
    fileBlacklist: [/\.map|.js/],
  }),
  new PreloadWebpackPlugin({
    rel: 'prefetch',
    include: 'allChunks',
    fileBlacklist: [/\.css/],
  }),

Unfortunately this doesn't achieve anything as the first instance of PreloadWebpackPlugin gets completely overwritten by the second one.

I'm wondering if you already have a solution, otherwise it could be good to either transform the options into an array and pass multiple configuration for different type of files or extend the current object to allow multiple rel and related rules.

It shouldn't be so difficult to implement but please let me know.

Thanks in advance.

I tried your config and it works, resulting html has prefetch and preload links. I myself have config which preloads fonts and prefetches js and css and it works. Perhaps something else doesn't work in yout case. Are you using version 2?

          I tried your config and it works, resulting html has prefetch and preload links. I myself have config which preloads fonts and prefetches js and css and it works. Perhaps something else doesn't work in yout case. Are you using version 2?
     new PreloadWebpackPlugin({
        rel: 'preload',
        as(entry) {
          if (/\.(woff(2)?)(\?v=[0-9]\.[0-9]\.[0-9])?$/.test(entry)) {
            return 'font';
          }
        },
        fileWhitelist: [/\.(woff(2)?)(\?v=[0-9]\.[0-9]\.[0-9])?$/],
        include: 'allAssets'
      }),
      new PreloadWebpackPlugin({
        rel: 'prefetch',
      }),

Originally posted by @lkarmelo in #22 (comment)

Support imagesrcset and imagesizes

Are there any plans for supporting imagesrcset and imagesizes attributes for preloading responsive images?
Could perhaps be done by adding the following to this line:

if (attributes.as === 'image') {
  const { imagesrcset, imagesizes } = options
  if (imagesrcset) {
    attributes.imagesrcset = imagesrcset
    if (imagesizes) {
      attributes.imagesizes = imagesizes
    }
  }
}

Is it possible to use glob patterns with chunk names? How to preload specific chunks?

I'm attempting to preload initial chunks, as well as some worker scripts using webpack chain in Vue, but I'm struggling to get it to work. Is there something I'm missing here?

    if (config.plugins.has('preload')) {
      config.plugin('preload').tap((options) => {
        options[0] = {
          rel: 'preload',
          include: {
            chunks: ['*.worker.js'],
            type: 'initial'
          },
          fileBlacklist: [/\.map$/, /hot-update\.js$/]
        };
        return options;
      });
    }

Ignore chunk via webpack comment

I tried add webpack comment to disable prefetch/preload, but the chunck still builded into html as rel="prefetch".
Is it possible to disable it without modify blacklist in webpack config?

My code:

await import(/* webpackPrefetch: false */ 'some-module')

Spurious </link> closing tags are being emitted

The link elements injected into the HTML are not being properly marked as void elements. This causes html-webpack-plugin to generate spurious </link> closing tags upon serialization. (Harmless, but ugly.)

The fix is to explicitly set voidTag: true in the created link tags here.
Even better, probably, might be to use createHtmlTagObject to create the tag object.

Preloads images as script and assets that are not in the config

This is my config

  new PreloadWebpackPlugin({
    rel: 'preload',
    include: ['chunk-vendors', 'app'],
  }),

And the output

<link href="/css/age-gate.7b50d0a2.css" rel="preload" as="style">
<link href="/css/filepond.4a740c40.css" rel="preload" as="style">
<link href="/css/home.bebc5034.css" rel="preload" as="style">
<link href="/css/profile.f65713e7.css" rel="preload" as="style">
<link href="/css/recover.03a0e9c6.css" rel="preload" as="style">
<link href="/css/register.03a0e9c6.css" rel="preload" as="style">
<link href="/css/reset.03a0e9c6.css" rel="preload" as="style">
<link href="/img/staropramen-code-upload.dddbfe8c.png" rel="preload" as="script">
<link href="/img/staropramen-gameplay-bg.7994297a.jpg" rel="preload" as="script">
<link href="/img/staropramen-gameplay.fbf554b4.png" rel="preload" as="script">
<link href="/img/staropramen-prize-1.3e2c7064.png" rel="preload" as="script">
<link href="/img/staropramen-prize-2.d8f7e2b5.png" rel="preload" as="script">
<link href="/img/staropramen-prize-3.7ca5d10d.png" rel="preload" as="script">
<link href="/img/staropramen-products.7b055b44.png" rel="preload" as="script">
<link href="/img/staropramen-top-1.3166b1bb.png" rel="preload" as="script">
<link href="/img/staropramen-top-2.1a4b787f.png" rel="preload" as="script">
<link href="/img/staropramen-top-3.cd3e4c21.png" rel="preload" as="script">
<link href="/img/staropramen-top-background.9c018782.jpg" rel="preload" as="script">
<link href="/js/age-gate.9f33f640.js" rel="preload" as="script">
<link href="/js/code-upload.53d3511b.js" rel="preload" as="script">
<link href="/js/filepond.2a5b5c23.js" rel="preload" as="script">
<link href="/js/home.597ddb30.js" rel="preload" as="script">
<link href="/js/not-found.c0d5b062.js" rel="preload" as="script">
<link href="/js/profile.da945b71.js" rel="preload" as="script">
<link href="/js/recover.1685671a.js" rel="preload" as="script">
<link href="/js/register.80d10696.js" rel="preload" as="script">
<link href="/js/registration-status.ea7cd7d2.js" rel="preload" as="script">
<link href="/js/reset.300794f1.js" rel="preload" as="script">
<link href="/manifest.json" rel="preload" as="script">
<link href="/sitemap.xml" rel="preload" as="script">

Which is completely wrong, am I missing something?

Edit:

After adding a blacklist I managed to remove images and stuff, but the chunks are still not filtered correctly

  new PreloadWebpackPlugin({
    rel: 'preload',
    fileBlacklist: [/\.(png|jpe?g|xml|json)/],
    include: ['chunk-vendors', 'app'],
  }),
<link href="/css/age-gate.7b50d0a2.css" rel="preload" as="style">
<link href="/css/filepond.4a740c40.css" rel="preload" as="style">
<link href="/css/home.bebc5034.css" rel="preload" as="style">
<link href="/css/profile.f65713e7.css" rel="preload" as="style">
<link href="/css/recover.03a0e9c6.css" rel="preload" as="style">
<link href="/css/register.03a0e9c6.css" rel="preload" as="style">
<link href="/css/reset.03a0e9c6.css" rel="preload" as="style">
<link href="/js/age-gate.e3a04a39.js" rel="preload" as="script">
<link href="/js/code-upload.0079298a.js" rel="preload" as="script">
<link href="/js/filepond.2a5b5c23.js" rel="preload" as="script">
<link href="/js/home.843bef30.js" rel="preload" as="script">
<link href="/js/not-found.4edda045.js" rel="preload" as="script">
<link href="/js/profile.833ea73d.js" rel="preload" as="script">
<link href="/js/recover.c6698a96.js" rel="preload" as="script">
<link href="/js/register.252c43b0.js" rel="preload" as="script">
<link href="/js/registration-status.f4c99ba8.js" rel="preload" as="script">
<link href="/js/reset.92daf21c.js" rel="preload" as="script">

Using webpack 5 and the latest html webpack plugin

Document 'allAssets'

I was trying to preload Wasm resource. Only by looking at the source, I found an option include: 'allAssets' that allows to preload such binary resources, but it doesn't seem to be documented in the README.

Is there any way to prefetch resource after page loaded?

    /* config.plugin('preload') */
    new PreloadPlugin(
      {
        rel: 'preload',
        include: 'initial',
        fileBlacklist: [
          /\.map$/,
          /hot-update\.js$/
        ]
      }
    ),
    /* config.plugin('prefetch') */
    new PreloadPlugin(
      {
        rel: 'prefetch',
        include: 'asyncChunks'
      }
    )

These settings start download prefetch async chunks when preload chunk-venders is still downloading.I think this can damage the first screen performance.Is there any way to prefetch resource after page loaded?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.