1. function fallbackHTML(html) {
  2. // Check if the fallback HTML is defined.
  3. if (typeof fallbackHTML === 'undefined') {
  4. return null; // No fallback defined.
  5. }
  6. // Return the fallback HTML.
  7. return fallbackHTML;
  8. }
  9. // Example fallback HTML (can be defined globally or passed as an argument)
  10. const fallbackHTML = `
  11. <!DOCTYPE html>
  12. <html>
  13. <head>
  14. <title>Fallback</title>
  15. <style>
  16. body { font-family: sans-serif; }
  17. </style>
  18. </head>
  19. <body>
  20. <h1>Something went wrong.</h1>
  21. <p>Please try again later.</p>
  22. </body>
  23. </html>
  24. `;
  25. // Example usage (replace with your actual fallback logic)
  26. function loadPage(url) {
  27. fetch(url)
  28. .then(response => {
  29. if (!response.ok) {
  30. // Fallback if the main page fails to load.
  31. const fallback = fallbackHTML();
  32. if (fallback) {
  33. document.documentElement.innerHTML = fallback; // Replace the content of the page
  34. } else {
  35. document.documentElement.innerHTML = "<h1>Error loading page</h1>";
  36. }
  37. }
  38. return response.text();
  39. })
  40. .then(text => {
  41. document.documentElement.innerHTML = text; // Load the main page content
  42. })
  43. .catch(error => {
  44. // Fallback if there's a network error.
  45. const fallback = fallbackHTML();
  46. if (fallback) {
  47. document.documentElement.innerHTML = fallback; // Replace the content of the page
  48. } else {
  49. document.documentElement.innerHTML = "<h1>Error loading page</h1>";
  50. }
  51. });
  52. }

Add your comment