@CacheLookup Annotation in PageFactory
@CacheLookup Annotation in PageFactory
The @CacheLookup
annotation is used in Selenium’s PageFactory model to cache WebElement references after they are first located. This means that instead of finding the element on the web page each time it’s accessed, the previously found reference is reused, which can improve performance if the page is static and the element doesn’t change.
Every time when a method is called on a WebElement, the driver will first find it on the current page and then simulate the action on the WebElement. There are cases where we will be working with a basic page, and we know that we will find the element on the page every time we look for it, In such cases we can use annotation ‘@CacheLookup‘ which is another annotation in page factory
<span class="hljs-annotation">@FindBy</span>(name=<span class="hljs-string">"username"</span>)
<span class="hljs-annotation">@CacheLookup</span>
<span class="hljs-keyword">private</span> WebElement userName;
@CacheLookup Annotation
In Selenium, the @CacheLookup
annotation is used to mark a WebElement so that PageFactory stores it in memory after it is first found on the page. We will mark annotation @CacheLookup to WebElements to indicate that it never changes (that is, that the same instance in the DOM will always be used)
✅ When to Use @CacheLookup
CacheLookup attribute can be used to instruct the InitElements() method to cache the element once its located and so that it will not be searched over and over again – this is useful when the elements that are always going to be there
(For AJAX based applications, it may not work where the DOM changes based on user action on the page). Otherwise every time when we use a Web Element the WebDriver will go and search it again
-
The element is static and does not reload or change during the test.
-
You’re accessing the element multiple times, and want to avoid repeated DOM searches.
❌ When Not to Use @CacheLookup
But whenever we use @CacheLookup annotation, we will be losing one of the page factory benefit as it will find the element once and then keep a reference to it, hence, we are more likely to see StaleElementExceptions.
-
The element is dynamic, e.g., changes on refresh, AJAX updates, or re-renders.
-
You navigate to different pages or refresh the same page — the element reference becomes stale, leading to
StaleElementReferenceException
.
Table
With @CacheLookup |
Without @CacheLookup |
|
---|---|---|
DOM Lookup | Once (cached) | Every access |
Performance | Faster | Slower |
Risk of Stale Reference | High (if dynamic) | Low |
Best for | Static elements | Dynamic/changing elements |
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/CacheLookup.html
Selenium Tutorials on this website: