Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions dev.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ app.use(async (req, res) => {

res.status(resp.status);

// Doc responses from the runtime connector lack Cache-Control, causing
// browsers to apply heuristic caching (RFC 7234) and silently serve stale
// content. Setting no-cache ensures the browser always revalidates via
// If-Modified-Since / If-None-Match while still caching for 304 efficiency.
if (source === 'docs' && !headers.has('cache-control')) {
headers.set('cache-control', 'no-cache');
}

// Set headers properly for Express
headers.forEach((value, key) => {
res.set(key, value);
Expand Down
89 changes: 71 additions & 18 deletions hlx_statics/blocks/fragment/fragment.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ import {
import {
isLocalHostEnvironment
} from '../../scripts/lib-adobeio.js';

// Dedup concurrent config validation fetches within the same page load.
// Multiple callers (top-nav, buttons, side-nav) all loadFragment the same
// config URL — this ensures only ONE network request is made.
const configValidationCache = new Map();

/**
* Loads a fragment.
* @param {string} path The path to the fragment
Expand Down Expand Up @@ -62,30 +68,77 @@ import {

const hashCode = (s) => s.split('').reduce((a, b) => (((a << 5) - a) + b.charCodeAt(0)) | 0, 0);
const fragmentHash = `${hashCode(fetchPathUrl)}`;
const fragmentLmKey = `${fragmentHash}_lm`;
let main;

if (sessionStorage.getItem(fragmentHash)) {
main = document.createElement('main');
main.innerHTML = sessionStorage.getItem(fragmentHash);
} else {
const resp = await fetch(fetchPathUrl);
if (resp.ok) {
const htmlText = await resp.text();
const isConfig = lastPrefix === 'config';
const cachedHtml = sessionStorage.getItem(fragmentHash);

if (isConfig) {
// Config validation: one fetch per page load, shared across all callers.
// Uses If-Modified-Since revalidation (cache: 'no-cache') so the browser
// leverages its HTTP cache for 304 responses while always checking freshness.
if (!configValidationCache.has(fragmentHash)) {
configValidationCache.set(fragmentHash, (async () => {
try {
const resp = await fetch(fetchPathUrl, { cache: 'no-cache' });
if (!resp.ok) return;

const currentLm = resp.headers.get('last-modified');
const storedLm = sessionStorage.getItem(fragmentLmKey);
const storedHtml = sessionStorage.getItem(fragmentHash);

if (currentLm && storedLm === currentLm && storedHtml) {
console.log(`[fragment] config valid (last-modified: ${currentLm})`);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These console.log are used to verify if the last-modified is correctly checked, do we want to keep these in code?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's fine to leave these ones in as they help debug.

return;
}

console.log(`[fragment] config ${storedHtml ? 'stale' : 'miss'} (${storedLm} → ${currentLm})`);
const htmlText = await resp.text();
const temp = document.createElement('main');
if (isLocalHostForDocs) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
const mainContent = doc.querySelector('main');
if (mainContent) temp.innerHTML = mainContent.innerHTML;
} else {
temp.innerHTML = htmlText;
}
sessionStorage.setItem(fragmentHash, temp.innerHTML);
if (currentLm) sessionStorage.setItem(fragmentLmKey, currentLm);
} catch (e) {
console.warn('[fragment] config validation failed', e);
}
})());
}

await configValidationCache.get(fragmentHash);
const content = sessionStorage.getItem(fragmentHash);
if (content) {
main = document.createElement('main');
main.innerHTML = content;
}
} else if (cachedHtml) {
main = document.createElement('main');
if (isLocalHostForDocs ) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
const mainContent = doc.querySelector('main');
if (mainContent) {
main.innerHTML = mainContent.innerHTML;
main.innerHTML = cachedHtml;
} else {
const resp = await fetch(fetchPathUrl);
if (resp.ok) {
const htmlText = await resp.text();
main = document.createElement('main');
if (isLocalHostForDocs) {
const parser = new DOMParser();
const doc = parser.parseFromString(htmlText, 'text/html');
const mainContent = doc.querySelector('main');
if (mainContent) {
main.innerHTML = mainContent.innerHTML;
}
} else {
main.innerHTML = htmlText;
}
} else {
main.innerHTML = htmlText;
sessionStorage.setItem(fragmentHash, main.innerHTML);
}

sessionStorage.setItem(fragmentHash, main.innerHTML);
}
}

// Always run initialization for both cached and fresh fragments
if (main) {
Expand Down
Loading