Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Kingwl
Copy link

@Kingwl Kingwl commented Mar 26, 2021

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
Copy link
Author

Kingwl commented Mar 26, 2021

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

@Kingwl Kingwl reopened this Mar 26, 2021
@Kingwl
Copy link
Author

Kingwl commented Mar 31, 2021

I'm not sure what happend.

@stale
Copy link

stale bot commented Jan 9, 2022

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
Copy link
Author

Kingwl commented Jan 9, 2022

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