How to Detect the First Time a User Lands on Your Website

I had a site with a pre-roll fade-in animation on the home page. It worked great, but it soon got really tiresome to have to wait for the animation to complete every time I returned to the site’s home page. I needed a way to detect if the user got to the home page from somewhere else on my site, or if they got there for the first time, either from another site or by typing in the URL manually.

At first, I added a query string that would skip the animation and I just used that URL within my site. But, that made the URL ugly, and if someone shared that link with someone, they would never see the animation. Plus, it didn’t stop the animation from happening if someone used the browser’s “back” button.

I also thought about using cookies or local storage.

Eventually, I found a much better solution that doesn’t involve mangling the URL. It is completely invisible in fact! It detects whether the sending page is your site’s domain and whether the user got to your page using the browsers “back” or “forward” buttons!

The JavaScript Solution

Here’s the JS code to detect whether someone came from within your site!

if ( (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD ) ||
            ( document.referrer.indexOf("") >=0 ) )

The first part of the “if” statement detects when the user used the browser’s “forward” or “back” buttons to get to the page.

The second part detects whether the referrer was part of your site or not!

Do whatever you need to do between the curly brackets! Or, negate the whole thing to do something only when someone lands on your page from another site or when they typed in the URL manually in a browser.

Here is an example of this technique in action.

Hope this helps. Let me know how it worked for you in the comments! – Brian


Please Leave a Question or Comment

Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Inline Feedbacks
View all comments
David Lain
David Lain
1 day ago

Super useful! Being able to detect where users come from within the site opens up so many possibilities for personalization and analytics. Thanks for sharing this insightful trick!