Site Optimizer is a lightweight and efficient JavaScript library that automatically enhances your website's performance, speed, and user experience without requiring manual intervention. Simply integrate it, and let it optimize your site on the fly! β‘
- Loads images and iframes only when they are about to be displayed.
- Improves initial load speed and reduces unnecessary data usage.
- Uses
IntersectionObserver
for optimal performance.
Example:
<img data-lazy data-src="image.jpg" alt="Lazy Loaded Image">
<iframe data-lazy data-src="video.mp4"></iframe>
- Registers a Service Worker to cache static assets.
- Enhances load speed for repeat visits.
- Allows offline access for cached pages.
Setup:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service-worker.js');
}
- Tracks Core Web Vitals like CLS (Cumulative Layout Shift), FID (First Input Delay), and LCP (Largest Contentful Paint).
- Helps diagnose performance issues.
Example:
import('web-vitals').then(({ getCLS, getFID, getLCP }) => {
getCLS(console.log);
getFID(console.log);
getLCP(console.log);
});
- Implements retry logic for network requests.
- Uses timeout to prevent long waits.
Example:
SiteOptimizer.fetchData('https://api.example.com/data')
.then(data => console.log(data))
.catch(error => console.error(error));
- Defer loading of non-essential scripts to improve render speed.
- Moves scripts with
data-defer
attribute to the end of<body>
.
Example:
<script data-defer data-src="analytics.js"></script>
- Prevents excessive function calls by delaying (debounce) or limiting (throttle) execution.
Debounce Example: (Executes only after a delay)
const optimizedSearch = SiteOptimizer.debounce(() => {
console.log('Searching...');
}, 300);
input.addEventListener('input', optimizedSearch);
Throttle Example: (Executes at most once in a given time frame)
const optimizedScroll = SiteOptimizer.throttle(() => {
console.log('Scrolling event fired');
}, 500);
window.addEventListener('scroll', optimizedScroll);
- Enables smooth scrolling for all browsers.
- Uses polyfill for older browsers.
<script src="site-optimizer.js"></script>
Simply initialize the optimizer after the page loads:
document.addEventListener('DOMContentLoaded', () => {
SiteOptimizer.init();
});
Method | Description |
---|---|
SiteOptimizer.init() |
Initializes all optimizations. |
SiteOptimizer.$(selector) |
Shortcut for document.querySelector . |
SiteOptimizer.$$(selector) |
Shortcut for document.querySelectorAll . |
SiteOptimizer.on(element, event, callback) |
Adds an event listener. |
SiteOptimizer.debounce(func, delay) |
Returns a debounced function. |
SiteOptimizer.throttle(func, limit) |
Returns a throttled function. |
SiteOptimizer.fetchData(url, options, retries, timeout) |
Fetches data with retry logic and timeout. |
This project is open-source and available under the MIT License.
For any questions or contributions, feel free to reach out!
Happy Optimizing! π