Many blogs built with WordPress include ads from networks like Google AdSense and Baidu. But have you noticed that when WordPress references external resources, a slow response from the external server can cause your page to hang for a long time? To avoid this problem, we can defer ad code loading in WordPress, effectively speeding things up. Based on my testing, this code snippet works for deferring ads from major ad networks including Baidu, Google, and NetEase.
Here’s how to do it:
- Go to the WordPress admin panel, select Edit under Appearance, and find the statement
<?php the_content(); ?>(or a related function). Add the following before that statement:
<div id="myad"></div>
- Open your
footer.phpfile and add the following code before</body>:
if (is_single()) :
<div id="span_myads">
<!-- AD code -->
//Insert your ad code here
<!-- AD coed end-->
</div>
<script type="text/javascript">
document.getElementById("myad").innerHTML = document.getElementById("span_myads").innerHTML;
document.getElementById("span_myads").innerHTML = "";
</script>
endif;
</div>
- Open your
style.cssfile and add the following CSS:
#myad{float:left;margin:20px 10px 10px 40px;}
Let me explain the principle: web page elements load in order. We place an empty div where the ad should appear, then at the very end of page loading, we call the Google ad JavaScript, generate the ad, and replace the content of that original div. Of course, if you use this code directly, it will load ads on single post pages (since my blog’s ads only appear on article pages), and the CSS styling is my own.
You’ll need to modify the code according to your own situation. As for deferring ads in the sidebar or homepage, I won’t go into detail here — the approach is essentially the same. With the code above, you just need to tweak a few functions.