最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Exclude JS file from 404 error page

programmeradmin2浏览0评论

I have a custom tracking system in place which works with an include of a .js file in the footer of each page. Unfortunately some high traffic sites are including images from my site which are already removed. therefor the 404 error page of my theme is frequenty hit and those users are registered aswell as website visitors even though I dont want them to count.

Long story short: I want to provent that tracking.js file to load on the 404 error page. What would be the best way to do that?

I have a custom tracking system in place which works with an include of a .js file in the footer of each page. Unfortunately some high traffic sites are including images from my site which are already removed. therefor the 404 error page of my theme is frequenty hit and those users are registered aswell as website visitors even though I dont want them to count.

Long story short: I want to provent that tracking.js file to load on the 404 error page. What would be the best way to do that?

Share Improve this question edited Jun 10, 2019 at 6:59 norman.lol 3,2413 gold badges30 silver badges35 bronze badges asked Jun 8, 2019 at 18:05 JustinJustin 1111 bronze badge 1
  • How are you adding the JS file to the site? With wp_enqueue_script()? – Jacob Peattie Commented Jun 9, 2019 at 4:21
Add a comment  | 

2 Answers 2

Reset to default 1

There is is_404(). I normally use it to do just the opposite, to add CSS and JS animations which are specific to the 404 error page. In your case that would be:

function wpse_339946() {

    if ( ! is_404() ) {
        wp_enqueue_script( 'tracking-js', get_template_directory_uri() . '/js/tracking.js' );
    }
}

add_action( 'wp_enqueue_scripts', 'wpse_339946' );

You could use the is_page() function on your footer to check if it is a 404 page, then don't add the js code if it is the 404 page. Added the commenter is right - a 404 is a response, not a page, so you can't test for it. (I blame temporary insanity...) So .... the answer is now....

updated Create a 404 page template that doesn't include the js code. That template will be used is a page request causes a '404' response.

Related to your question: I also worry about incomplete tracking because of ad blockers. So developed a server-side tracker that sends GA tracking data. Ad-blockers never see it, so I get full tracking data. (With GDPR notifications, of course.) Perhaps an alternative for you.

发布评论

评论列表(0)

  1. 暂无评论