Grow your CSS skills. Land your dream job.

Load js only if class is present on page?

  • # August 16, 2012 at 3:04 pm

    Perhaps this is a JS or a PHP question, not sure.

    Is there a way to load a script tag ONLY if the class of say, “.accordion” is on that page? I’m trying to minimize http requests for a WordPress site. :)

    # August 16, 2012 at 5:04 pm

    Yeah. Assuming you have jQuery loaded up:

    if($('.accordion').length){
    $('', {
    id: 'script',
    src: 'http://url.goes/here.js'
    }).appendTo('body');
    };
    # September 7, 2012 at 12:04 pm

    Very nice. Thank you!

    # September 7, 2012 at 6:12 pm

    I like to do this by registering my scripts in my functions.php using wp_register_script(). Then when the element which requires that script asset is present use the wp_enqueue_script() function to make sure that it loads.
    http://codex.wordpress.org/Function_Reference/wp_register_script

    For example: in functions.php:

    `wp_register_script( ‘jquery-bigtarget’, ‘http://url.to/jquery.bigtarget.1.0.1.js’, false, false, true );`

    inside some IF statement:

    `if ( $this ) wp_enqueue_script(‘jquery-bigtarget);`

    I like to keep all my initializations in my main script.js file, so there is a nice way to put the init there but to render it useless when the necessary asset doesn’t load.

    `if ( if ( $.isFunction($.fn.bigTarget) ) {
    code goes here
    }`

    # October 15, 2012 at 7:19 pm

    Wow, this is really helpful! Thank you @TechStudio!

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".