Skip to content

wrap scripts into dom loaded event listener if defer is specified#10753

Open
Kingwl wants to merge 3 commits into
react:mainfrom
Kingwl:InlineChunkHtmlPlugin_defer
Open

wrap scripts into dom loaded event listener if defer is specified#10753
Kingwl wants to merge 3 commits into
react:mainfrom
Kingwl:InlineChunkHtmlPlugin_defer

Conversation

@Kingwl

@Kingwl Kingwl commented Mar 26, 2021

Copy link
Copy Markdown

Fixes #10752

This PR add a branch to detect what if defer attribute has been specified on script tag or not.
And if so, All script will be wrapped into a DOMContentLoaded event listener.

Here's an example for the changes:

We have a script:

alert(document.body.innerText);

And a html tmeplate:

<html>
    <body>
        <div>foo</div>
    </body>
</html>

And a webpack config:

module.exports = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index.js'
    },
    plugins: [
        new HtmlWebpackPlugin({
          inject: true,
          template: 'index.html'
        }),
        new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/.*/])
    ]
}

Before changes:

<html>
<head>
    <script>alert(document.body.innerText);</script>
</head>
<body>
    <div>foo</div>
</body>
</html>

And It will caused an exception:

Uncaught TypeError: Cannot read property 'innerText' of null

** before changes with blocking **

<html>
<body>
    <div>foo</div>
    <script>alert(document.body.innerText);</script>
</body>
</html>

That works fine.

After changes (whatever blocking or not):

<html>
<body>
    <div>foo</div>
    <script>alert(document.body.innerText);</script>
</body>
</html>

And everything works fine.

@Kingwl Kingwl changed the title wrap into dom loaded event listener if defer is specified wrap scripts into dom loaded event listener if defer is specified Mar 26, 2021
@Kingwl Kingwl closed this Mar 26, 2021
@Kingwl

Kingwl commented Mar 26, 2021

Copy link
Copy Markdown
Author

Oh I just realized It will break If there's listener for DOMContentLoaded in the script.

@Kingwl Kingwl reopened this Mar 26, 2021
@Kingwl

Kingwl commented Mar 31, 2021

Copy link
Copy Markdown
Author

I'm not sure what happend.

@stale

stale Bot commented Jan 9, 2022

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had any recent activity. It will be closed in 5 days if no further activity occurs.

@stale stale Bot added the stale label Jan 9, 2022
@Kingwl

Kingwl commented Jan 9, 2022

Copy link
Copy Markdown
Author

emmmmm, ping

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

InlineChunkHtmlPlugin should respect defer attribute.

2 participants