最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add defer or async attribute to wp_add_inline_script? - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 5

wp_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.

发布评论

评论列表(0)

  1. 暂无评论