First I enqueue a script using:
wp_enqueue_script( "script", plugins_url( "/test/js/script.js", PATH ), array("jquery"), VERSION, true );
Then I'm inserting an inline script after "script".
wp_add_inline_script( "script", "console.log('hello world');" );
Now I need to add defer or async attribute to my inline script, is there a way to do this to a script embedded by wp_add_inline_script() ?
First I enqueue a script using:
wp_enqueue_script( "script", plugins_url( "/test/js/script.js", PATH ), array("jquery"), VERSION, true );
Then I'm inserting an inline script after "script".
wp_add_inline_script( "script", "console.log('hello world');" );
Now I need to add defer or async attribute to my inline script, is there a way to do this to a script embedded by wp_add_inline_script() ?
Share Improve this question asked Mar 14, 2018 at 15:44 NurgielNurgiel 1805 silver badges12 bronze badges2 Answers
Reset to default 5wp_enqueue_script( "script", plugins_url( "/test/js/script.js", PATH ), array("jquery"), VERSION, true );
wp_script_add_data( 'script', 'async/defer' , true );
see more
I know this isn't what you're looking for, but defer
doesn't work unless there's a src
attribute. I.e. it doesn't work on inline scripts.
From the MDN docs:
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded. Scripts with the defer attribute will prevent the DOMContentLoaded event from firing until the script has loaded and finished evaluating. Warning: This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. The defer attribute has no effect on module scripts — they defer by default. Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse. async has a similar effect in this case.