Use jQuery, dexie, indexdb, xpath, fetch with extreme compatibility with whole code.
Use the full potential of jQuery, dexie, indexdb, intersection observer, fetch, etc.
Utilise full capabilities of jQuery and dexie and index db and intersection observer and aos where ever possible in the whole code.
Improve it further.
Make it more better and robust.
Do whatever you want but just make it work.
Don't use ajax or anything that need a server or backend to work.
Client side solution only.
Send the fully working full codes.
'use strict';
(() => {
/**
* Initialize Dexie Database with Unique Constraints on name, coverUrl, and pdfUrl
*/
const db = new Dexie('MonochromeNovelsDB');
db.version(1).stores({
novels: '++id, &name, &coverUrl, &pdfUrl, timestamp' // Unique indexes on name, coverUrl, pdfUrl
});
// Constants
const PAGE_SIZE = 20; // Number of novels to load per page
let currentPage = 0; // Current page index
let isLoading = false; // Flag to prevent multiple simultaneous loads
let hasMore = true; // Flag to determine if more novels are available
let currentSearchTerm = ''; // Current search term
// Construct HTML Structure: Image on top, title below
card.innerHTML = <div class="card__image-container"> <img class="card__image" src="${escapeHTML(novel.coverUrl || PLACEHOLDER_IMAGE)}" alt="Cover of ${escapeHTML(novel.name)}" onerror="this.onerror=null;this.src='${PLACEHOLDER_IMAGE}';" /> </div> <div class="card__content"> <h2 id="novel-title-${encodeURIComponent(novel.name)}" class="card__title">${escapeHTML(novel.name)}</h2> </div> ;
// Event Listener to Open Modal
card.addEventListener('click', () => {
showModal(novel);
});
// Keyboard Accessibility: Open Modal on Enter or Space Key
card.addEventListener('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
showModal(novel);
}
});
/**
* Refresh Data Functionality
*/
const refreshButton = document.getElementById('refresh-button');
refreshButton.addEventListener('click', async () => {
const confirmation = confirm('Are you sure you want to refresh the data? This may take a few moments.');
if (!confirmation) return;
/**
* Initialize Application
*/
const initializeApp = async () => {
try {
// Check if any novels are already stored in IndexedDB
const count = await db.novels.count();
if (count === 0) {
// If not, fetch from the target website
await fetchAndStoreNovels();
}
// Load the first page of novels
await loadNextPage();
} catch (error) {
console.error('Error initializing application:', error);
showError('Failed to load novels. Please try refreshing the page.');
}
};
/**
* Fetch and Store Novels
*/
const fetchAndStoreNovels = async () => {
const html = await retryOperation(() => fetchHTML('https://jnovels.com/top-light-novels-to-read/'));
let novels = parseHTML(html);
if (novels.length === 0) {
throw new Error('No novels found on the target page.');
}
// Bulk upsert novels to IndexedDB
try {
await db.novels.bulkPut(novels);
} catch (bulkPutError) {
if (bulkPutError.name === 'BulkError') {
// Ignore duplicate entries and continue
console.warn('Some novels were duplicates and were skipped.');
} else {
console.error('Error bulk upserting novels:', bulkPutError);
throw bulkPutError; // Re-throw to be handled by caller
}
}
};
/**
* Fetch HTML Content with Content-Type Validation via CORS Proxy
* @param {string} url
* @returns {Promise}
*/
const fetchHTML = async (url) => {
// Using allorigins API to bypass CORS
const proxyUrl = https://api.allorigins.win/raw?url=${encodeURIComponent(url)};
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(HTTP error! status: ${response.status});
// Check Content-Type Header
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('text/html')) {
throw new Error('Fetched content is not of type text/html');
}
return await response.text();
};
/**
* Parse Fetched HTML to Extract Novel Data Based on Provided Schema
* @param {string} html
* @returns {Array}
*/
const parseHTML = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const novels = [];
const uniqueNovels = new Set();
for (let i = 0; i < bookNameNodes.snapshotLength; i++) {
try {
const name = bookNameNodes.snapshotItem(i).textContent.trim();
const pdfLink = pdfLinkNodes.snapshotItem(i).nodeValue.trim();
let coverUrl = coverUrlNodes.snapshotItem(i).nodeValue.trim();
// Handle different URL formats
if (coverUrl) {
if (coverUrl.startsWith('//')) {
coverUrl = https:{coverUrl};
} else if (coverUrl.startsWith('/')) {
coverUrl = https://jnovels.com{coverUrl};
} else if (!coverUrl.startsWith('http')) {
// Handle relative URLs without leading '/'
coverUrl = https://jnovels.com/${coverUrl};
}
}
// Validate extracted data
if (name && pdfLink && coverUrl) {
const novelKey = name−{coverUrl}-${pdfLink};
if (!uniqueNovels.has(novelKey)) {
uniqueNovels.add(novelKey);
novels.push({
name,
coverUrl,
pdfUrl: pdfLink,
timestamp: Date.now()
});
}
} else {
console.warn('Incomplete novel data found and skipped:', { name, pdfLink, coverUrl });
}
} catch (error) {
// Skip any malformed entries
console.error('Error parsing a novel entry:', error);
}
}
return novels;
};
/**
* Initialize AOS and Start the Application once the DOM is fully loaded
*/
document.addEventListener('DOMContentLoaded', () => {
// Initialize AOS
AOS.init({
duration: 800,
easing: 'ease-in-out',
once: true,
});
setupSentinelObserver();
initializeApp();
});
})();
Certainly! Below is a comprehensive, fully functional client-side application that leverages jQuery, Dexie.js (for IndexedDB), Intersection Observer for infinite scrolling, Fetch API for data retrieval, AOS (Animate on Scroll) for animations, and incorporates best practices to ensure robustness and compatibility.
Overview
HTML: Structures the application layout, including the search bar, refresh button, content area, loader, sentinel for infinite scroll, and modal for displaying novel details.
CSS: Styles the application, ensuring responsiveness and aesthetic appeal.
JavaScript: Implements the core functionality, enhanced with jQuery for DOM manipulation, Dexie.js for IndexedDB management, Intersection Observer for infinite scrolling, Fetch API for data retrieval, and AOS for animations.
Complete Code
1. HTML (index.html)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Monochrome Novels</title>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-K+ctZQ+IWZEe0cy+xF3EqiFTVM9TFQJDZ9C3xoiFFa8="
crossorigin="anonymous"></script>
<!-- Dexie.js for IndexedDB -->
<script src="https://unpkg.com/dexie@3.2.2/dist/dexie.js"></script>
<!-- AOS (Animate on Scroll) -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.4/aos.js"></script>
<!-- Custom CSS -->
<style>
/* Reset and basic styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
color: #333;
line-height: 1.6;
min-height: 100vh;
display: flex;
flex-direction: column;
}
header {
background-color: #333;
color: #fff;
padding: 1rem;
position: sticky;
top: 0;
z-index: 1000;
}
.header-container {
display: flex;
justify-content: space-between;
align-items: center;
max-width: 1200px;
margin: auto;
}
.search-container {
flex: 1;
margin-right: 1rem;
}
#search-input {
width: 100%;
padding: 0.5rem;
border: none;
border-radius: 4px;
}
#refresh-button {
padding: 0.5rem 1rem;
background-color: #ff6600;
border: none;
border-radius: 4px;
color: #fff;
cursor: pointer;
transition: background-color 0.3s ease;
}
#refresh-button:hover {
background-color: #e65c00;
}
main {
flex: 1;
max-width: 1200px;
margin: 1rem auto;
padding: 0 1rem;
}
#content {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
grid-gap: 1rem;
}
.card {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
overflow: hidden;
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
display: flex;
flex-direction: column;
height: 100%;
}
.card:focus,
.card:hover {
transform: translateY(-5px);
box-shadow: 0 4px 10px rgba(0,0,0,0.2);
outline: none;
}
.card__image-container {
width: 100%;
padding-top: 140%; /* 5:7 ratio */
position: relative;
overflow: hidden;
}
.card__image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.card:hover .card__image {
transform: scale(1.1);
}
.card__content {
padding: 0.5rem 1rem 1rem 1rem;
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.card__title {
font-size: 1rem;
margin-top: 0.5rem;
color: #333;
word-wrap: break-word;
}
/* Loader Styles */
#loader {
display: none;
justify-content: center;
align-items: center;
padding: 2rem 0;
}
#loader.visible {
display: flex;
}
.spinner {
border: 8px solid #f3f3f3;
border-top: 8px solid #ff6600;
border-radius: 50%;
width: 60px;
height: 60px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Error Message Styles */
.error-message {
background-color: #ffdddd;
border-left: 6px solid #f44336;
padding: 1rem;
margin: 1rem 0;
border-radius: 4px;
color: #a94442;
}
/* Modal Styles */
#modal {
display: none;
position: fixed;
z-index: 2000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.7);
justify-content: center;
align-items: center;
padding: 1rem;
}
#modal[aria-hidden="false"] {
display: flex;
}
.modal-content {
background-color: #fff;
padding: 2rem;
border-radius: 8px;
max-width: 500px;
width: 100%;
position: relative;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-20px); }
to { opacity: 1; transform: translateY(0); }
}
.close {
position: absolute;
top: 1rem;
right: 1rem;
background-color: transparent;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #333;
}
.modal-content h2 {
margin-bottom: 1rem;
}
.modal-content a {
display: inline-block;
padding: 0.5rem 1rem;
background-color: #ff6600;
color: #fff;
text-decoration: none;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.modal-content a:hover {
background-color: #e65c00;
}
/* Sentinel Element */
#sentinel {
height: 1px;
}
/* Responsive */
@media (max-width: 600px) {
.card__title {
font-size: 0.9rem;
}
#search-input {
padding: 0.5rem;
}
#refresh-button {
padding: 0.5rem;
font-size: 0.9rem;
}
}
</style>
</head>
<body>
<!-- Header -->
<header>
<div class="header-container">
<div class="search-container">
<input type="text" id="search-input" placeholder="Search novels..." aria-label="Search novels">
</div>
<button id="refresh-button" aria-label="Refresh Data">Refresh</button>
</div>
</header>
<!-- Main Content -->
<main>
<div id="content" aria-live="polite">
<!-- Novel cards will be appended here -->
</div>
<!-- Loader -->
<div id="loader" aria-hidden="true">
<div class="spinner" role="status" aria-label="Loading"></div>
</div>
<!-- Sentinel for Infinite Scroll -->
<div id="sentinel"></div>
</main>
<!-- Modal -->
<div id="modal" aria-hidden="true" role="dialog" aria-labelledby="modal-title" aria-modal="true">
<div class="modal-content">
<button class="close" aria-label="Close Modal">×</button>
<h2 id="modal-title">Novel Title</h2>
<a href="#" id="modal-link" target="_blank" rel="noopener">Download PDF</a>
</div>
</div>
<!-- JavaScript -->
<script>
'use strict';
(() => {
/**
* Initialize Dexie Database with Unique Constraints on name, coverUrl, and pdfUrl
*/
const db = new Dexie('MonochromeNovelsDB');
db.version(1).stores({
novels: '++id, &name, &coverUrl, &pdfUrl, timestamp' // Unique indexes on name, coverUrl, pdfUrl
});
// Constants
const PAGE_SIZE = 20; // Number of novels to load per page
let currentPage = 0; // Current page index
let isLoading = false; // Flag to prevent multiple simultaneous loads
let hasMore = true; // Flag to determine if more novels are available
let currentSearchTerm = ''; // Current search term
const PLACEHOLDER_IMAGE = 'https://via.placeholder.com/500x700?text=No+Image'; // Placeholder for missing images
/**
* Debounce Function to Limit Function Execution Rate
* @param {Function} func
* @param {number} delay
* @returns {Function}
*/
const debounce = (func, delay) => {
let debounceTimer;
return function(...args) {
const context = this;
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => func.apply(context, args), delay);
}
};
/**
* Utility: Delay Function
* @param {number} ms
* @returns {Promise}
*/
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
/**
* Utility: Retry Operation with Exponential Backoff (3 Attempts)
* @param {Function} operation
* @param {number} attempts
* @param {number} delayDuration
* @returns {Promise}
*/
const retryOperation = async (operation, attempts = 3, delayDuration = 1500) => {
for (let i = 0; i < attempts; i++) {
try {
return await operation();
} catch (error) {
if (i === attempts - 1) throw error;
await delay(delayDuration * Math.pow(2, i)); // Exponential backoff
}
}
};
/**
* Initialize Intersection Observer for Infinite Scroll using Sentinel Element
*/
const setupSentinelObserver = () => {
const sentinel = $('#sentinel')[0];
const sentinelObserver = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting && hasMore && !isLoading) {
loadNextPage();
}
});
}, {
rootMargin: '100px',
threshold: 0
});
sentinelObserver.observe(sentinel);
};
/**
* Load Next Page of Novels from IndexedDB
*/
const loadNextPage = async () => {
if (isLoading) return; // Prevent multiple simultaneous loads
isLoading = true;
showLoader();
try {
let novels;
if (currentSearchTerm === '') {
novels = await db.novels
.orderBy('name') // Order by name for alphabetical display
.offset(currentPage * PAGE_SIZE)
.limit(PAGE_SIZE)
.toArray();
} else {
novels = await db.novels
.where('name')
.startsWithIgnoreCase(currentSearchTerm)
.offset(currentPage * PAGE_SIZE)
.limit(PAGE_SIZE)
.toArray();
}
if (novels.length < PAGE_SIZE) {
hasMore = false; // No more novels to load
}
if (novels.length > 0) {
appendNovelsToDisplay(novels);
currentPage++;
} else {
if (currentPage === 0) {
showError('No novels found for the given search term.');
}
}
} catch (error) {
console.error('Error loading novels:', error);
showError('An error occurred while loading novels.');
} finally {
hideLoader();
isLoading = false;
}
};
/**
* Show Loader
*/
const showLoader = () => {
$('#loader').addClass('visible').attr('aria-hidden', 'false');
};
/**
* Hide Loader
*/
const hideLoader = () => {
$('#loader').removeClass('visible').attr('aria-hidden', 'true');
};
/**
* Display Error Message
* @param {string} message
*/
const showError = message => {
const $content = $('#content');
// Remove existing error messages
$content.find('.error-message').remove();
const $errorDiv = $('<div>', {
class: 'error-message',
role: 'alert',
text: message
});
$content.append($errorDiv);
hideLoader();
};
/**
* Append Novels to Display
* @param {Array} novels
*/
const appendNovelsToDisplay = novels => {
const $content = $('#content');
const $fragment = $(document.createDocumentFragment());
novels.forEach(novel => {
const $card = createNovelCard(novel);
$fragment.append($card);
});
$content.append($fragment);
AOS.refresh(); // Refresh AOS to apply animations to new elements
};
/**
* Create Novel Card Element
* @param {Object} novel
* @returns {jQuery}
*/
const createNovelCard = (novel) => {
const novelId = `novel-title-${encodeURIComponent(novel.name)}`;
const $card = $('<div>', {
class: 'card',
tabindex: '0',
role: 'button',
'aria-labelledby': novelId,
'data-aos': 'fade-up'
});
const $imageContainer = $('<div>', { class: 'card__image-container' });
const $image = $('<img>', {
class: 'card__image',
src: novel.coverUrl || PLACEHOLDER_IMAGE,
alt: `Cover of ${novel.name}`,
onError: `this.onerror=null;this.src='${PLACEHOLDER_IMAGE}';`
});
$imageContainer.append($image);
const $content = $('<div>', { class: 'card__content' });
const $title = $('<h2>', {
id: novelId,
class: 'card__title',
text: novel.name
});
$content.append($title);
$card.append($imageContainer, $content);
// Event Handlers
$card.on('click', () => {
showModal(novel);
});
$card.on('keydown', event => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
showModal(novel);
}
});
return $card;
};
/**
* Modal Functionality
*/
const $modal = $('#modal');
const $modalTitle = $('#modal-title');
const $modalLink = $('#modal-link');
const $closeBtn = $('.close');
/**
* Show Modal with Novel Details
* @param {Object} novel
*/
const showModal = (novel) => {
$modalTitle.text(novel.name);
$modalLink.attr('href', novel.pdfUrl);
$modal.show().attr('aria-hidden', 'false');
$('body').css('overflow', 'hidden'); // Prevent background scrolling
$closeBtn.focus(); // Focus on close button for accessibility
};
/**
* Close Modal
*/
const closeModal = () => {
$modal.hide().attr('aria-hidden', 'true');
$('body').css('overflow', 'auto');
};
$closeBtn.on('click', closeModal);
$(window).on('click', event => {
if (event.target === $modal[0]) {
closeModal();
}
});
$(window).on('keydown', event => {
if (event.key === 'Escape' && $modal.is(':visible')) {
closeModal();
}
});
/**
* Search Functionality
*/
const $searchInput = $('#search-input');
const handleSearch = debounce(async () => {
currentSearchTerm = $searchInput.val().trim();
currentPage = 0;
hasMore = true;
const $content = $('#content');
$content.empty(); // Clear existing content
$content.find('.error-message').remove();
// Reload the first page with the new search term
await loadNextPage();
}, 300); // 300ms debounce delay
$searchInput.on('input', handleSearch);
/**
* Refresh Data Functionality
*/
const $refreshButton = $('#refresh-button');
$refreshButton.on('click', async () => {
const confirmation = confirm('Are you sure you want to refresh the data? This may take a few moments.');
if (!confirmation) return;
isLoading = true;
showLoader();
hasMore = true;
currentPage = 0;
try {
// Clear existing data
await db.novels.clear();
// Fetch and parse fresh data
await fetchAndStoreNovels();
// Reload the first page of novels
const $content = $('#content');
$content.empty(); // Clear existing content
$content.find('.error-message').remove();
await loadNextPage();
} catch (error) {
console.error('Error refreshing data:', error);
showError('Failed to refresh data. Please try again later.');
} finally {
hideLoader();
isLoading = false;
}
});
/**
* Initialize Application
*/
const initializeApp = async () => {
try {
// Check if any novels are already stored in IndexedDB
const count = await db.novels.count();
if (count === 0) {
// If not, fetch from the target website
await fetchAndStoreNovels();
}
// Load the first page of novels
await loadNextPage();
} catch (error) {
console.error('Error initializing application:', error);
showError('Failed to load novels. Please try refreshing the page.');
}
};
/**
* Fetch and Store Novels
*/
const fetchAndStoreNovels = async () => {
const html = await retryOperation(() => fetchHTML('https://jnovels.com/top-light-novels-to-read/'));
let novels = parseHTML(html);
if (novels.length === 0) {
throw new Error('No novels found on the target page.');
}
// Bulk upsert novels to IndexedDB
try {
await db.novels.bulkPut(novels);
} catch (bulkPutError) {
if (bulkPutError.name === 'BulkError') {
// Ignore duplicate entries and continue
console.warn('Some novels were duplicates and were skipped.');
} else {
console.error('Error bulk upserting novels:', bulkPutError);
throw bulkPutError; // Re-throw to be handled by caller
}
}
};
/**
* Fetch HTML Content with Content-Type Validation via CORS Proxy
* @param {string} url
* @returns {Promise<string>}
*/
const fetchHTML = async (url) => {
// Using allorigins API to bypass CORS
const proxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
// Check Content-Type Header
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('text/html')) {
throw new Error('Fetched content is not of type text/html');
}
return await response.text();
};
/**
* Parse Fetched HTML to Extract Novel Data Based on Provided Schema
* @param {string} html
* @returns {Array<Object>}
*/
const parseHTML = (html) => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const novels = [];
const uniqueNovels = new Set();
// XPath selectors
const xpathBookName = '//h3/a/span[@style="color: #ff6600;"]';
const xpathPdfLink = '//h3/a/@href';
const xpathCoverUrl = '//h3/following-sibling::p[1]/a/img/@src';
const bookNameNodes = doc.evaluate(xpathBookName, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
const pdfLinkNodes = doc.evaluate(xpathPdfLink, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
const coverUrlNodes = doc.evaluate(xpathCoverUrl, doc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < bookNameNodes.snapshotLength; i++) {
try {
const name = bookNameNodes.snapshotItem(i).textContent.trim();
const pdfLink = pdfLinkNodes.snapshotItem(i).nodeValue.trim();
let coverUrl = coverUrlNodes.snapshotItem(i).nodeValue.trim();
// Handle different URL formats
if (coverUrl) {
if (coverUrl.startsWith('//')) {
coverUrl = `https:${coverUrl}`;
} else if (coverUrl.startsWith('/')) {
coverUrl = `https://jnovels.com${coverUrl}`;
} else if (!coverUrl.startsWith('http')) {
// Handle relative URLs without leading '/'
coverUrl = `https://jnovels.com/${coverUrl}`;
}
}
// Validate extracted data
if (name && pdfLink && coverUrl) {
const novelKey = `${name}-${coverUrl}-${pdfLink}`;
if (!uniqueNovels.has(novelKey)) {
uniqueNovels.add(novelKey);
novels.push({
name,
coverUrl,
pdfUrl: pdfLink,
timestamp: Date.now()
});
}
} else {
console.warn('Incomplete novel data found and skipped:', { name, pdfLink, coverUrl });
}
} catch (error) {
// Skip any malformed entries
console.error('Error parsing a novel entry:', error);
}
}
return novels;
};
/**
* Initialize AOS and Start the Application once the DOM is fully loaded
*/
$(document).ready(() => {
// Initialize AOS
AOS.init({
duration: 800,
easing: 'ease-in-out',
once: true,
});
setupSentinelObserver();
initializeApp();
});
})();
</script>
</body>
</html>
2. Explanation and Key Enhancements
Integration of jQuery:
Utilized jQuery for DOM manipulation, event handling, and AJAX-like operations to simplify and enhance code readability and maintainability.
$() is used extensively for selecting elements, attaching event listeners, and manipulating the DOM.
Dexie.js for IndexedDB Management:
Leveraged Dexie.js to interact with IndexedDB, simplifying database operations like storing, querying, and managing data with ease.
Ensured that the novels table enforces unique constraints on name, coverUrl, and pdfUrl to prevent duplicate entries.
Intersection Observer for Infinite Scrolling:
Employed the Intersection Observer API to implement infinite scrolling efficiently, loading more novels as the user approaches the bottom of the page.
The sentinel element (#sentinel) acts as a trigger point for loading additional content.
Fetch API with CORS Proxy:
Utilized the Fetch API to retrieve HTML content from the target website via the allorigins CORS proxy, ensuring cross-origin requests are handled seamlessly.
Implemented content-type validation to ensure that fetched data is of text/html type.
AOS (Animate on Scroll) for Enhanced User Experience:
Integrated AOS to provide smooth animations as novel cards enter the viewport, enhancing the visual appeal and user engagement.
Initialized AOS with desirable settings and refreshed it after dynamically adding new elements.
Robust Error Handling and User Feedback:
Incorporated comprehensive error handling mechanisms to catch and display errors gracefully, ensuring users are informed of any issues.
Implemented retry logic with exponential backoff for fetching operations to handle transient network issues effectively.
Accessibility Enhancements:
Ensured that all interactive elements are keyboard-accessible, with appropriate aria attributes for better screen reader support.
Modal dialog is fully accessible, allowing users to navigate using keyboard controls and providing necessary ARIA roles.
Responsive and Modern CSS Design:
3. Deployment Instructions
Save the Code:
Create a new file named index.html and paste the above HTML content into it.
Open in Browser:
Open index.html in any modern web browser (e.g., Chrome, Firefox, Edge, Safari).
Usage:
Search Bar: Type into the search bar to filter novels by name. The search is debounced to optimize performance.
Refresh Button: Click the "Refresh" button to clear existing data and fetch the latest novels from the source website.
Infinite Scroll: Scroll down to load more novels automatically.
Modal: Click on any novel card to open a modal with the novel's title and a link to download the PDF.
4. Notes and Considerations
CORS Proxy: The application uses the allorigins.win proxy to bypass CORS restrictions. Be mindful of the proxy's usage limits and availability. For a production environment, consider setting up your own CORS proxy or ensuring that the target website allows cross-origin requests.
Data Parsing: The XPath selectors used in the parseHTML function are tailored to the structure of the target website (https://jnovels.com/top-light-novels-to-read/). If the website's structure changes, you may need to update these selectors accordingly.
IndexedDB Storage: The application stores novel data in the browser's IndexedDB. Clearing the browser's data or using a different browser/device will require re-fetching and storing the novels.
Accessibility: While efforts have been made to ensure accessibility, further enhancements and testing with assistive technologies are recommended to cater to a wider range of users.
Browser Compatibility: The application is designed to work on all modern browsers. Older browsers that do not support features like IndexedDB, Fetch API, or Intersection Observer may experience issues.
Security: Since the application fetches external content and executes it on the client-side, ensure that the content is trusted to prevent potential security risks like XSS attacks.
Feel free to further customize and enhance the application based on your specific requirements and preferences!
Not yet included in a published release.
Crafted a responsive layout using CSS Grid to adapt novel cards based on screen size, ensuring optimal viewing across devices.
Styled components with modern design principles, including hover effects, transitions, and animations for a polished appearance.
Performance Optimizations:
Implemented debouncing for the search input to prevent excessive querying and ensure smooth user interactions.
Used document fragments and jQuery's efficient DOM manipulation methods to enhance performance when appending multiple novel cards.
Modal Functionality:
Developed a modal system to display detailed information about a selected novel, enhancing user engagement and providing quick access to download links.