- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Load js only if class is present on page?
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. :)
Very nice. Thank you!
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
}`
Wow, this is really helpful! Thank you @TechStudio!