The Lodge is members-only design/dev videos and Office Hours.

Next Office Hours Session: "Implementing an SVG Icon System" Nov 30 - 6:00 PM Eastern

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

    This reply has been reported for inappropriate content.

    Yeah. Assuming you have jQuery loaded up:

    $('', {
    id: 'script',
    src: 'http://url.goes/here.js'
    # 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.

    For example: in functions.php:

    `wp_register_script( ‘jquery-bigtarget’, ‘’, 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.

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed