There is a JS file common to all pages. There is jQuery code that works with elements of a specific page. On pages that do not have the desired items, an error occurs. How to execute jQuery-code only on a specific page, without putting it into a separate file?

  • one
    if(el.length){ ... Выполнить .... } - HamSter

2 answers 2

Hmm, you can check the address and stop execution if the substring in the address is not found (if that, wrapping the code in (function(){ … })() so that you can use return ):

 if (location.pathname.indexOf('…') === -1) return; 

But it is better, of course, just to check if there are any necessary elements on the current page. For example:

 if ($('.element').length === 0) return; 
  • For some reason I didn’t guess the presence of elements :-) - Frontender

Try to compare location.pathname or location.href :

  //значения location.pathname, при которых будет запускаться ваш скрипт var pagesWithScript = ["/page1", "/page2"]; if (pagesWithScript.indexOf(location.pathname) != -1 ) { //ваш скрипт } 

location.pathname is the relative path to the page. For example, for https://example.com/page location.pathname = "/page"