When JavaScript is executed, the DOM may be modified, affecting the display of the page. By default, it is safe to load and execute JavaScript first, and then load and execute the subsequent code. When loading and executing JavaScript code, the loading and execution of the subsequent code will be stopped. This behavior is called blocking, and this mode is synchronous loading. If we can allow these JavaScripts to be downloaded and executed without affecting the execution of subsequent page code, the page loading speed will be improved to a certain extent. Let’s take the social network code as an example to demonstrate how toWordPress themeAsynchronously load social media sharing buttons to improve page loading speed.
What is JavaScript asynchronous loading?
Asynchronous loading means that when the browser downloads and executes JavaScript, it will not affect the loading and execution of subsequent code. There are many ways to implement asynchronous loading. The method introduced in this article is the most commonly used. This method is to use JS to create a Script element within the <script> tag on the page and insert it into the Document. This achieves non-blocking downloading of JavaScript code.
Benefits of asynchronous loading:
- Will increase page speed (reduce loading time). Colleagues loading and executing the page below do not need to wait for responses from other (social network) servers.
- The content of the website is relatively independent. If the server of the social network loads the supermarket, the content of the website will not be affected.
- It helps reduce user waiting time, reduce bounce rate, and is helpful for SEO.
- If users stay on our site for a longer period of time, they will be more likely to share our articles.
The following is a method to implement asynchronous loading of social network code in WordPress. It can be achieved in three steps. We can modify the following code as needed to load the files we need.
Step 1: Create JavaScript files
For example, we add the following code to a file called share.js and place it in the js folder in the theme root folder.
/* 异步加载分享按钮的 JavaScript */
(function(w, d, s) {
// 插入加载后的代码
function go(){
var js, fjs = d.getElementsByTagName(s)[0], load = function(url, id) {
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.src = url; js.id = id;
fjs.parentNode.insertBefore(js, fjs);
};
// 加载社交网络分享代码
load('//connect.facebook.net/en_US/all.js#xfbml=1', 'fbjssdk'); //Facebook
load('https://apis.google.com/js/plusone.js', 'gplus1js'); //Google+
load('//platform.twitter.com/widgets.js', 'tweetjs'); //Twitter
load('//platform.linkedin.com/in.js', 'lnkdjs'); // LinedIN
load('//assets.pinterest.com/js/pinit.js', 'pinitjs'); //Pinterest
}
if (w.addEventListener) {
w.addEventListener("load", go, false);
}
else if (w.attachEvent) {
w.attachEvent("onload",go);
}
}(window, document, 'script'));
If any friends have paid attention to the asynchronous loading statistics code of Baidu Statistics or Google Analytics, they will find that their code is similar to the code above.
Step 2: Load the share.js file into the theme
Add the following code to the themefunctions.phpIn the file:
/* 插入代码到主题的 functions.php */
function meks_load_scripts(){
//只在文章页面加载,如果需要在页面中加载,使用 "is_singular()",如果还需要在存档页面加载,直接去掉下面的判断语句即可。
if(is_single()){
wp_enqueue_script( 'meks_async_share', trailingslashit(get_template_directory_uri()).'/js/share.js', array( 'jquery' ));
}
}
add_action('wp_enqueue_scripts', 'meks_load_scripts');
Step 3: Place the HTML code into the theme’s template
The last step is to insert a “placeholder” in the theme’s template. After the script is executed, the share button will be filled in where the “placeholder” is inserted. It is best to use it in a loop. The code example is as follows:
<?php if( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_title(); ?>
<?php the_content(); ?>
<ul class="meks_share">
<!-- twitter -->
<li><a class="twitter-share-button" data-count="vertical" data-via="mekshq" data-url="<?php the_permalink() ?>"></a></li>
<!-- LinkedIN -->
<li><script type="IN/Share" data-counter="top" data-url="<?php the_permalink() ?>"></script></li>
<!-- facebook like -->
<li><div class="fb-like" data-send="false" data-layout="box_count" data-width="50" data-show-faces="false" data-href="<?php the_permalink() ?>"></div></li>
<!-- g+ -->
<li><g:plusone size="tall" data-href="<?php the_permalink() ?>"></g:plusone></li>
<!-- pinterest -->
<li><a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink() ?>&media=<?php echo wp_get_attachment_url( get_post_thumbnail_id() ); ?>&description=<?php echo urlencode(get_the_title()); ?>" class="pin-it-button" count-layout="vertical"><img border="0" src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a></li>
</ul>
<?php endwhile; ?>
<?php endif; ?>
In addition, there are two specialized JavaScript libraries to help us implement asynchronous loading. One isControlJS, one calledHeadJS, interested friends can pay attention.
