How to include scripts for Wordpress in one file so that they work on all pages?

  • 0
    A script that should run on one page raises an error on another (for example, Cannot read property 'addEventListener' of null). Do you need to split scripts into different files for different pages, for example, script-home.js or script-medie.js, or can you somehow make it so that you don't knock out errors?
    JavaScript Lilah Bowen, Mar 5, 2019

  • 3 Answers
  • 0
    In functions php, you can connect the required file to the required page.

  • 0
    const item = document.querySelector('.item')
    if(item) {
    item.addEventListener('click', e => {


    Use this design.
    Jasper Middleton

  • 0
    The documentation explicitly says how - the wp_enqueue_script function allows you to specify dependencies.

    Connect scripts according to the code of the VI and specify dependencies for dependent scripts.

    Use conditional WordPress tags to check if you are there and, depending on that, connect the necessary scripts.

    If the volume of js is large and logically divided into home-page.js (well, for example, because only there is a slider and in js it is) and single.js (loaded on a single page - for example, a script for comments) - then this is a sensible idea. And do not care what they say about performance - that individual files need to be compressed into one - they are one of those who do not know about the http / 2 protocol.

    You can also add scripts that can be separately taken out for logged in or for guests (for example, for a guest - a script for a pop-up login form)

    Likewise for css. WordPress is a powerful framework - it allows you to be smart.
    Evelyn Cantu

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!