8 posts
  • Has been part of the Envato Community for over 1 year
  • Located in Bosnia and Herzegovina
Ratko_Solaja says

Hello brave developers,

I have a question for you. I’ve been working with WordPress for quite some time, but there’s one little thing that keeps me awake at night. I want to put in a single .js file all of my script initialization’s – for example, let’s say I have two different pages, and one of them uses bxslider, while the other has bigvideo. Via wordpress you would normally load those script via wp_enqueue_script in functions.php

That’s ok, and via that and if(is_page_template()) or any other conditional argument I can decide when to load a certain script. But, if I have a file, with init for bigvideo and bxslider, and that one page uses only bxslider but not the bigvideo, I’m gonna get an error in console for bigvideo.

How can I init my scripts in one file but only if those scripts are required on the page?

I hope you understand what I’m talking about. Cheers.

1485 posts
  • Has referred 1+ members
  • Has sold $10,000+ on Envato Market
  • Has collected 10+ items on Envato Market
  • Made it to the Authors' Hall of Fame
+3 more
OriginalEXE says

It’s pretty simple.

jQuery( function( $ ) { // short for jQuery( document ).ready( function( $ ) {

    "use strict";

    var $bxSlider = $( '.bxslider' ),
        $bigVideo = $( '.bigvideo' );

    if ( $bxSlider.length ) { // bxslider markup found on current page, do something with it here...

        $bxSlider.each( function() {

            // your bxslider calls

        });

    }

    if ( $bigVideo.length ) { // bigvideo markup found on current page, do something with it here...

        $bigVideo.each( function() {

            // your bigvideo calls

        });

    }

});
8 posts
  • Has been part of the Envato Community for over 1 year
  • Located in Bosnia and Herzegovina
Ratko_Solaja says

Thanks mate. That’s it. I have been struggling with ‘typeof’ and those kind of things, never thought about this kind of approach.

by
by
by
by
by
by