| 开发者 |
palasthotel
greatestview janaeggebrecht |
|---|---|
| 更新时间 | 2026年8月4日 15:02 |
| 捐献地址: | 去捐款 |
| PHP版本: | 5.4 及以上 |
| WordPress版本: | 7.0.2 |
| 版权: | GPL-3.0-or-later |
| 版权网址: | 版权信息 |
wp_add_inline_script( 'my-handle', 'if (!("localStorage" in window)) { /* ... */ }', 'before' );
For code that has to run before anything paints, print it in wp_head directly.
Both are simpler, and neither breaks a Content Security Policy the way an inlined
file does — this plugin sets neither a nonce nor a hash, so a strict script-src
blocks its output.
For a script you do not control, dequeue it and re-add its content yourself:
add_action( 'wp_enqueue_scripts', function () { $handle = 'some-foreign-handle'; $src = wp_scripts()->registered[ $handle ]->src ?? null; if ( ! $src ) { return; } $path = ABSPATH . ltrim( wp_make_link_relative( $src ), '/' ); if ( ! is_readable( $path ) ) { return; } wp_dequeue_script( $handle ); wp_add_inline_script( 'some-handle-you-own', file_get_contents( $path ) ); }, 20 );
You decide there how the file is located, which is the part this plugin got wrong:
it resolved the path relative to the current working directory, so the result
depended on which entry script served the request.
Why it is being retired
The benefit it was written for has largely gone. Under HTTP/1.1 every file cost a
round trip, so inlining a small critical script was a real win. HTTP/2 and HTTP/3
multiplex requests and removed most of that cost, while inlining still gives up
browser caching — the code travels with every HTML response instead of being cached
once.
How it used to work
In some cases you cannot wait for a JavaScript file to load, even if it is placed early in the <head> section of your template. You can benefit from better performance, if you place the JavaScript code directly inside a <script> tag into the header. This is where this plugin comes in: It provides a filter inline_javascript_in_head_handles, which takes JavaScript handles, dequeues those scripts and echos their code content inline into the head section instead of linking them via a script tag.
Please beware that placing lots of JavaScript code inline in the <head> section can be critical! First you lose caching benefits and second the document size can increase easily. A general rule of thumb is that you should only consider JavaScript files for inline placement, which are critical and which have a file size lower than ~500 Bytes.
Example
`
add_action( 'wp_enqueue_scripts', 'my_scripts' );
function my_scripts() {
// Some critical script is enqueued
wp_enqueue_script( 'js-detection', get_template_directory_uri() . '/js/js-detection.js' );
}
/**
inline_javascript_in_head_handles filter from your theme or
plugin, then deactivate and delete the plugin. It stores no options and creates no
database tables, so nothing is left behind.inline_javascript_in_head_wrap_try_catch, which can add add a try catch wrapper around the JavaScript code.