Conditional Loading of JavaScript

  • iftekhar
  • Jun 28, 2015
  • 0 comment
  • 1503 Views
  • Print

In WP there are many cases when you might need to use certain JavaScript library files. Whether you want to simply add a nice looking Slideshow or any other widget that requires JavaScript files, they tend to slow down the page loading time. One way to speed up the page loading time could be calling the library files only when you need them.

WordPress Conditional TagWordPress Conditional Tag.

Let’s assume that you have a “portfolio” page and you want to showcase some of your work on that page using a JavaScript based slideshow. So, instead of calling the library files all the times (on other pages than the portfolio page), you can apply a condition so that the JavaScript files would only be called when the condition is met.

Let’s take a look at the following snippet to better understand the idea.

<?php if (is_page('portfolio')) {?>
<script src="script.js">
<php } ?>

Using the if condition we are asking to load script.js file only when the current page is portfolio page. If the current page is not portfolio page, this script.js file won’t be called. This way we can stop web browser from loading unnecessary JavaScript files which will ultimately speed up the overall page loading time. Definitely you can get creative with this but this is the basic idea.

Note: In HTML5 you won’t need to declare the “type” attribute as we all used to for “script” tags in the past. However, you should use the “type” attribute if your site is not HTML5 compatible.

In most of my WP related snippets you will find a number of such conditional tags. WP offers a pretty good codex page on this, feel free to check it out to get the most out of your snippet and to get creative with your site optimization.

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from Postable, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.