Conditional Loading and Targeting
Image to be inserted in the near future: Visual representation of different targeting options
One of Flexcode's most powerful features is the ability to control exactly where your code snippets appear. This allows you to:
- Target specific pages of your site
- Create page-specific functionality
- Optimize performance by loading code only where needed
By loading code only where it's needed, you can significantly improve your site's performance and reduce unnecessary resource usage.
Basic Targeting Options
Global Loading
The simplest targeting option is to load your snippet on every page of your site.
When to use:
- For global styles that affect your entire site
- For tracking scripts that should run everywhere
- For site-wide functionality like cookie notices
How to set up:
- When creating a new snippet, select "Global" from the page selector at the top
Global snippets run on every page of your site. Be careful with heavy scripts that might impact performance across your entire website.
Image to be inserted in the near future: Screenshot of the global option selected in the page selector
Specific Pages
Load your snippet only on certain pages.
When to use:
- For page-specific styling or functionality
- For content that only makes sense on certain pages
How to set up:
- When creating a new snippet, select the specific page from the page selector at the top
For optimal performance, always use specific page targeting when your code is only needed on certain pages.
Image to be inserted in the near future: Screenshot of a specific page selected in the page selector
Example: Contact Form Enhancement
Scenario: You want to add custom validation to your contact form, which is only on your Contact page.
- Select "Contact" from the page selector at the top
- Add a new file named "contact-validation.js" with the following code:
document.addEventListener('DOMContentLoaded', function() {
// Get the contact form
const contactForm = document.getElementById('contact-form');
// Only proceed if the form exists on this page
if (contactForm) {
contactForm.addEventListener('submit', function(event) {
// Get form fields
const nameField = document.getElementById('name');
const emailField = document.getElementById('email');
const messageField = document.getElementById('message');
// Simple validation
let isValid = true;
if (nameField.value.trim() === '') {
markInvalid(nameField, 'Please enter your name');
isValid = false;
} else {
markValid(nameField);
}
if (emailField.value.trim() === '' || !isValidEmail(emailField.value)) {
markInvalid(emailField, 'Please enter a valid email address');
isValid = false;
} else {
markValid(emailField);
}
if (messageField.value.trim() === '') {
markInvalid(messageField, 'Please enter your message');
isValid = false;
} else {
markValid(messageField);
}
// Prevent form submission if validation fails
if (!isValid) {
event.preventDefault();
}
});
}
// Helper functions
function markInvalid(field, message) {
field.classList.add('invalid');
// Create or update error message
let errorMessage = field.nextElementSibling;
if (!errorMessage || !errorMessage.classList.contains('error-message')) {
errorMessage = document.createElement('div');
errorMessage.classList.add('error-message');
field.parentNode.insertBefore(errorMessage, field.nextSibling);
}
errorMessage.textContent = message;
}
function markValid(field) {
field.classList.remove('invalid');
// Remove error message if it exists
const errorMessage = field.nextElementSibling;
if (errorMessage && errorMessage.classList.contains('error-message')) {
errorMessage.remove();
}
}
function isValidEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
});
Notice how the code first checks if the form exists with if (contactForm)
before adding event listeners. This prevents errors if the element isn't found and makes your code more robust.
- Add another file named "validation-styles.css" with the following code:
.invalid {
border: 2px solid #ff6b6b !important;
}
.error-message {
color: #ff6b6b;
font-size: 14px;
margin-top: 5px;
}
- Click "Deploy Changes" to apply your snippets to the Contact page
Suggested animation: GIF showing the form validation in action
Working with Different File Types
HTML Content
For HTML content, you'll use the dedicated HTML content box.
How to add HTML content:
- Select the target page from the page selector
- Enter your HTML in the HTML content box
- Click "Deploy Changes"
HTML injected through Flexcode will be added to your page's DOM. Be careful not to create duplicate IDs or conflicting elements that might break existing functionality.
Example: Adding a Notification Banner
Scenario: You want to add a notification banner to your homepage.
- Select "Home" from the page selector
- Enter the following in the HTML content box:
<div class="notification-banner">
<p>🔔 Special announcement: New features coming soon! <a href="/news">Learn more</a></p>
<button class="close-button">×</button>
</div>
- Add a new file named "notification_banner.css":
.notification-banner {
background-color: #4a6cf7;
color: white;
padding: 10px 20px;
text-align: center;
position: relative;
}
.notification-banner p {
margin: 0;
}
.notification-banner a {
color: white;
text-decoration: underline;
}
.close-button {
background: none;
border: none;
color: white;
position: absolute;
right: 10px;
top: 50%;
transform: translateY(-50%);
cursor: pointer;
font-size: 20px;
}
- Add another file named "notification_banner.js":
document.addEventListener('DOMContentLoaded', function() {
const closeButton = document.querySelector('.close-button');
const banner = document.querySelector('.notification-banner');
if (closeButton && banner) {
closeButton.addEventListener('click', function() {
banner.style.display = 'none';
// Remember that the user closed the banner
localStorage.setItem('bannerClosed', 'true');
});
// Check if the user previously closed the banner
if (localStorage.getItem('bannerClosed') === 'true') {
banner.style.display = 'none';
}
}
});
Using localStorage to remember user preferences (like closing a banner) creates a better user experience by respecting their choices across page loads.
- Click "Deploy Changes" to apply your banner to the homepage
Image to be inserted in the near future: Screenshot showing the notification banner on the homepage
CSS Files
For CSS styling, you'll add CSS files to your snippet.
How to add CSS:
- Select the target page from the page selector
- Click "Add File" and name it with a .css extension (e.g., "styles.css")
- Enter your CSS code
- Click "Deploy Changes"
To ensure your CSS overrides theme styles when needed, consider using more specific selectors or the !important
flag for critical styles (but use !important
sparingly).
JavaScript Files
For JavaScript functionality, you'll add JS files to your snippet.
How to add JavaScript:
- Select the target page from the page selector
- Click "Add File" and name it with a .js extension (e.g., "script.js")
- Enter your JavaScript code
- Click "Deploy Changes"
Be careful when manipulating elements that might also be targeted by your theme or plugins. Always check for existing event listeners and scripts that might conflict with your code.
Note: You can set the loading type to "deferred" to ensure your JavaScript runs after the DOM is loaded, which is often more efficient than using document.addEventListener('DOMContentLoaded', function() {...})
.
Best Practices for Flexcode Snippets
Organization Tips
- Use descriptive file names: Name your files according to their purpose (e.g., "header-enhancement.css" instead of "style1.css")
- Group related files: Keep related CSS and JS files together in the same snippet
- Comment your code: Add comments to explain what your code does, especially for complex snippets
Well-organized and commented code is much easier to maintain and update later. Your future self will thank you!
Performance Considerations
- Be specific with targeting: Only load snippets on pages where they're needed
- Minimize file size: Keep your CSS and JS files as small as possible
- Use efficient selectors: In CSS, use specific selectors to avoid performance issues
Heavy scripts or inefficient CSS selectors can significantly slow down your site. Always test your snippets for performance impact, especially on mobile devices.
Testing Your Snippets
Always test your snippets after deployment:
- Check different browsers
- Test on mobile devices
- Verify that your code works as expected
Use browser developer tools to check for JavaScript errors and CSS conflicts after deploying your snippets.
Image to be inserted in the near future: Diagram showing different testing scenarios
Example Use Cases
Adding Custom Fonts
Scenario: You want to add a custom Google Font to your entire site.
- Select "Global" from the page selector
- Add a new file named "custom-fonts.css":
/* Import the font from Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&display=swap');
/* Apply the font to all headings */
h1, h2, h3, h4, h5, h6 {
font-family: 'Montserrat', sans-serif;
}
Consider using font-display: swap to improve perceived loading performance when using custom fonts.
- Click "Deploy Changes"
Adding Analytics Tracking
Scenario: You want to add Google Analytics to your site.
- Select "Global" from the page selector
- Add a new file named "analytics.js":
// Google Analytics tracking code
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('send', 'pageview');
Remember that analytics tracking may require user consent in many jurisdictions. Consider implementing a consent mechanism to comply with privacy regulations like GDPR.
- Click "Deploy Changes"
Creating a Page-Specific Feature
Scenario: You want to add a countdown timer to a specific landing page.
- Select the landing page from the page selector
- Add a new file named "countdown.js":
document.addEventListener('DOMContentLoaded', function() {
// Add the countdown container to the page
const targetElement = document.querySelector('.entry-content');
if (targetElement) {
const countdownContainer = document.createElement('div');
countdownContainer.className = 'countdown-container';
countdownContainer.innerHTML = `
<h3>Limited Time Offer</h3>
<div class="countdown">
<div class="countdown-item">
<span id="countdown-days">00</span>
<span class="countdown-label">Days</span>
</div>
<div class="countdown-item">
<span id="countdown-hours">00</span>
<span class="countdown-label">Hours</span>
</div>
<div class="countdown-item">
<span id="countdown-minutes">00</span>
<span class="countdown-label">Minutes</span>
</div>
<div class="countdown-item">
<span id="countdown-seconds">00</span>
<span class="countdown-label">Seconds</span>
</div>
</div>
`;
targetElement.prepend(countdownContainer);
// Set the end date (YYYY, MM-1, DD, HH, MM, SS)
const endDate = new Date(2023, 11, 31, 23, 59, 59).getTime();
// Update the countdown every second
const countdownInterval = setInterval(function() {
const now = new Date().getTime();
const distance = endDate - now;
// Calculate days, hours, minutes, and seconds
const days = Math.floor(distance / (1000 * 60 * 60 * 24));
const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result
document.getElementById('countdown-days').textContent = days.toString().padStart(2, '0');
document.getElementById('countdown-hours').textContent = hours.toString().padStart(2, '0');
document.getElementById('countdown-minutes').textContent = minutes.toString().padStart(2, '0');
document.getElementById('countdown-seconds').textContent = seconds.toString().padStart(2, '0');
// If the countdown is over, clear the interval
if (distance < 0) {
clearInterval(countdownInterval);
document.querySelector('.countdown-container').innerHTML = '<h3>Offer Expired</h3>';
}
}, 1000);
}
});
Remember that JavaScript months are zero-indexed (0-11), which is why December is represented as 11 in the example above.
- Add a new file named "countdown.css":
.countdown-container {
background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
padding: 20px;
border-radius: 8px;
text-align: center;
margin-bottom: 30px;
}
.countdown-container h3 {
margin-top: 0;
color: white;
}
.countdown {
display: flex;
justify-content: center;
gap: 15px;
}
.countdown-item {
background: rgba(255, 255, 255, 0.9);
border-radius: 5px;
padding: 10px;
min-width: 60px;
}
.countdown-item span {
display: block;
}
#countdown-days, #countdown-hours, #countdown-minutes, #countdown-seconds {
font-size: 24px;
font-weight: bold;
color: #f54ea2;
}
.countdown-label {
font-size: 12px;
color: #666;
}
Make sure your custom elements like this countdown timer are responsive. Consider adding media queries to adjust the layout on smaller screens.
- Click "Deploy Changes"
Image to be inserted in the near future: Screenshot showing the countdown timer on the landing page