Async or defer for script tag in WordPress

Use any attributes for script tag in WordPress

Using function wp_enqueue_script for add scripts in WordPress does not allow to indicating attributes of a script such as async defer etc. Here, we describe how resolve this problem and also use wp_enqueue_script for enqueue of jQuery, Bootstrap by using CDN.

Intro

At the start self career, most WordPress developers, for enqueue of styles or scripts use usual tags and Further they'll know about "best practices", that how it do is right, with the assistance functions wp_enqueue_style and wp_enqueue_script. Next level of knowledge niceties of work with WordPress, are understanding that, use the function for add any script, does not allow execute of scripts are asynchronously, using async, defer. Also, you can have trouble if you should enable Bootstrap or jQuery that by using CDN, because for it need use attributes of integrity and crossorigin. .

Quick info: How we know, recommended are scripts and place in the footer of site. It's peculiar care about a user, that allow at first download HTML-content and work with it, and then download and execute scripts. However, in the some cases, there is need add some scripts in the header or inside of the body tag (before footer). In this case, when browser will come up to script, it at first execute it, and after then will show rest of page. It's the synchronously of behavior not always is convenient, and in order for scripts execute are asynchronously, that is download of page not depend on download of scripts, use attributes async or defer. The difference is that: async, as opposed to defer, doesn't wait until the whole HTML-document ready. Also, async does not support order of enqueue scripts.

Resolve of the problem

So, are we should give up recommendation the WordPress team, about the correctly add scripts or enuqueue they by manually? No, because add of manually it's a bad practice, that should not be used if you want have a clean code. For resolve this problem are you can use next decision:

Pay attention, that use this function could only after call wp_enqueue_script, that is at time of the function call you should initialize $handle for each calling scripts - "jquery", "bootstrap", etc.

P.S. Remember, in HTML5, attribute "type='text/javascript'" doesn't use.

Sources:

  1. https://learn.javascript.ru/external-script
  2. https://stackoverflow.com/questions/44827134/wordpress-script-with-integrity-and-crossorigin

 

Leave Comment

Your email address will not be published. Required fields are marked *