Loading javascript conditionally in WordPress functions.php

I created a child theme of the TwentyTwelve theme in WordPress for my photography website.

In the photo gallery pages, clicking on a thumbnail image either triggers Fancybox or Photoswipe, depending on the screen size (if <500px Photoswipe is used as it’s probably a mobile device).

Read More

For better performance I would like to load only the required javascript, Fancybox or Photoswipe, but not both of them.

  • I’m not using plugins for Fancybox/Photoswipe but load them in the child theme functions.php using wp_enqueue_style and wp_enqueue_script

  • the choice between Fancybox/Photoswipe is made in another javascript file, also enqueued in functions.php: according to the result of jQuery(window).width(); it triggers either Fancybox or Photoswipe on certain elements:

    jQuery(document).ready(function() {
    
        windows_size = jQuery(window).width();
    
        if(  windows_size > 500) {                  // Load Fancybox
    
           jQuery(".brick a").fancybox({
    
           [...]
    
        else {          // Load Photoswipe
    
           jQuery(".brick a").photoSwipe({
    
           [...]
    
  • I cannot use any of the WP functions like is_page(…), as both scripts are fired on the same page

  • I don’t know if it would be possible, using WordPress, to load all required files for Photoswipe (js and css) in the javascript above

  • I’d rather not use the user-agent to detect a mobile device

I searched on Google and on StackOverflow but couldn’t find any answer specifically related to WordPress and this situation.

Thanks for your help.

Related posts

Leave a Reply

1 comment