Why Use Component Detection?
Instead of loading scripts globally and checking for elements in your code:- Faster pages (less JavaScript to parse)
- Cleaner code (no existence checks needed)
- Fewer errors (script won’t run in wrong context)
Setting Up Component Detection
1
Open your script
Go to your site and open the script you want to configure.
2
Find Component Selector
In the script settings panel, find Component Selector.
3
Enter a CSS selector
Enter any valid CSS selector:
4
Save
The script will now only load on pages where that element exists.
Selector Examples
Class Selector
slider class.
ID Selector
hero-video exists.
Data Attribute
data-lightbox attribute.
Data Attribute with Value
Combined Selectors
Multiple Elements (OR)
Common Patterns
Animation Library Scripts
Only load GSAP animations when animated elements exist: Selector:[data-animate]
Form Handling
Only load validation on pages with forms: Selector:form[data-validate]
Third-Party Widgets
Only load Calendly script on pages with the embed: Selector:.calendly-inline-widget
Video Players
Only load video player code when videos exist: Selector:[data-video-player]
Component Detection vs Page Targeting
Both control where scripts load, but they work differently:| Feature | Page Targeting | Component Detection |
|---|---|---|
| Based on | URL path | DOM elements |
| Checks | Before page loads | After DOM ready |
| Best for | Section-based sites | Component-based sites |
| Example | /blog/* pages | Elements with .slider |
Using Both Together
You can combine them for precise control:- Page Targeting:
/services/* - Component Selector:
.pricing-calculator
Best Practices
Use data attributes for explicit targeting
Use data attributes for explicit targeting
Data attributes make intent clear and don’t conflict with styling:
Be specific with selectors
Be specific with selectors
Avoid overly broad selectors that might match unexpected elements:
Document your selectors
Document your selectors
Add comments in your scripts explaining what selector triggers them:
Test on multiple pages
Test on multiple pages
Verify the script loads where expected and doesn’t load where it shouldn’t.
Debugging
If a script isn’t loading when expected:-
Check the selector: Open browser DevTools and run:
If it returns
null, the element doesn’t exist. - Check for typos: Selectors are case-sensitive for IDs and data attributes.
- Check timing: The element must exist when the page loads. Dynamically added elements won’t trigger component detection.
-
Enable debug mode: Add
?debug=trueto your URL to see loader logs: