I have a javascript snippet that I want to inject into the footer of the page. It’s a tracking code, let’s say similar to Google analytics. It has no dependencies, it’s a standalone snippet.
I can do something like this
function render_tracking_code(){
wp_enqueue_script( 'depends-js', 'https://rdiv.com/dummy.js', array(), '0.01', true );
wp_add_inline_script( 'depends-js', 'aWholeBunchOfJavascriptCode' );
}
add_action( 'wp_enqueue_scripts', 'render_tracking_code' );
Seems a little stupid (dummy.js is a blank file), but works. Is there a way to skip the dependency?
wp_add_inline_style()
– without dependency
The wp_add_inline_style()
can be used without a source file dependency.
Here’s an example from @Flix:
wp_register_style( 'dummy-handle', false );
wp_enqueue_style( 'dummy-handle' );
wp_add_inline_style( 'dummy-handle', '* { color: red; }' );
where we would hook this into the wp_enqueue_scripts
action.
wp_add_inline_script()
– without dependency
According to ticket #43565, similar will be supported for wp_add_inline_script()
in version 4.9.9
5.0
(thanks to @MarcioDuarte, @dev101 and @DaveRomsey for the verification in comments):
wp_register_script( 'dummy-handle-header', '' );
wp_enqueue_script( 'dummy-handle-header' );
wp_add_inline_script( 'dummy-handle-header', 'console.log( "header" );' );
that will display the following in the header, i.e.between the <head>...</head>
tags:
<script type="text/javascript">
console.log( "header" );
</script>
To display it in the footer:
wp_register_script( 'dummy-handle-footer', '', [], '', true );
wp_enqueue_script( 'dummy-handle-footer' );
wp_add_inline_script( 'dummy-handle-footer', 'console.log( "footer" );' );
The default of $position
input argument in wp_add_inline_script()
is 'after'
. The 'before'
value prints it above 'after'
.