WordPress.org

Make WordPress Core

Opened 2 months ago

Last modified 4 weeks ago

#51124 new feature request

Can we get an additional parameter in wp_add_inline_script to set the script type?

Reported by: hcabrera Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version:
Component: Script Loader Keywords: good-first-bug needs-patch
Focuses: Cc:

Description

Hi everyone,

This is probably a feature that not many developers out there will use but I think it would be nice to have.

One of my plugins uses wp_add_inline_script to inject an inline script into the page. Said inline script gets assigned text/javascript as type automatically and there doesn't seem to be a way to change that (if there is please let me know and I'll gladly close this ticket.)

My plugin needs said inline script to contain a JSON string and so it currently hooks into script_loader_tag to change its type to application/json which feels a bit like a hack. It would be nice if we could set the script type via parameter (eg. wp_add_inline_script( 'some-handle', '...', 'before', 'application/json' );) (or maybe via filter hook before script_loader_tag happens?)

Thoughts?

Change History (1)

#1 @Otto42
4 weeks ago

  • Keywords good-first-bug needs-patch added

+1

This is a good idea. Additionally, the script tag can also be used for adding structured data using type="application/ld+json".

See here for more information: https://developers.google.com/search/docs/guides/intro-structured-data

Also, given that the text/javascript is the default for scripts, having type="text/javascript" there is not needed, and the latest W3 validation tool actually returns a warning for it with "The type attribute is unnecessary for JavaScript resources."

So it might be worth removing that default as well, and allowing for registered scripts to change the type via some data attached to the handle. Then only output the type attribute when it's explicitly set by the code.

Note: See TracTickets for help on using tickets.