Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End WP – loading javascripts

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #186552
    taxicss
    Participant

    Hi,
    Just want to ask on what’s the preferred or better way of loading javascripts on WordPress.

    So, i have a “responsiveslides.js” library that is only used on my homepage. I also have “owlcarousel.js” library that is also being used only on my gallery page. And i have other js files that are needed on specific pages.

    Is it better to combine all those js libraries in one file or I will just load them on their specific pages using conditional statements on my functions.php?

    Thanks.

    #186572
    Senff
    Participant

    You shouldn’t combine the scripts, just use the wp_enqueue_script function, which is the “proper” way.

    You’d end up with something like this:

    function load_scripts() {
        if( is_front_page() ) {
            wp_enqueue_script( 'homescript', get_theme_part( THEME_JS . '/responsiveslides.js' ), array( 'jquery' ), null, true );
        }
        if( is_page(42) ) {
            wp_enqueue_script( 'galleryscript', get_theme_part( THEME_JS . '/owlcarousel.js' ), array( 'jquery' ), null, true );
        }
        if( is_page(123) ) {
            wp_enqueue_script( 'otherstuff', get_theme_part( THEME_JS . '/some-other-script.js' ), array( 'jquery' ), null, true );
        }
    }
    
    add_action( 'wp_enqueue_scripts', 'load_scripts' );
    

    Of course you need to check the paths to the scripts, as well as the page IDs of the pages in question.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.