In the event that the link to the online CSS file is no longer working, utilize the local


The issue:


Currently, I am utilizing the w3.css to style my website. However, there is a recurring problem with the stability of the w3schools.com site.

Whenever the site goes down for maintenance, it affects the appearance of my website in a negative way.

To mitigate this issue, I have stored a local copy of the w3.css on my computer and server hosting my website.

Online Link:

<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">

Local Link:

<link rel="stylesheet" href="../css/w3.css">

The question at hand:


How can I detect when the link pointing to w3schools is inactive? This would prompt me to switch to the local w3.css file. Any suggestions on how to achieve this?

1)Check for broken links

2)Load the local css before the main website loads


In conclusion


Have major corporations found effective solutions for this issue? If multiple critical webservices go offline, it could spell catastrophe for the entire company...

Being new to web development, any advice or insights are greatly appreciated. Thank you.


Edit:(Consideration)

Is it possible to load both the

local(...site hosted on a server)
and w3schools files simultaneously, even though this may impact site loading times?

Answer №1

You can achieve this functionality using PHP. Although I haven't personally tested it, it is likely to work.

Simply place the following code snippet inside the <head> tag of your HTML document:

<?php

if (isDomainAvailable('http://www.w3schools.com')){
    echo '<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">';
} else {
    echo '<link rel="stylesheet" href="../css/w3.css">';
}

// Function to check if a domain is available
function isDomainAvailable($domain)
{
    // Check if a valid URL is provided
    if (!filter_var($domain, FILTER_VALIDATE_URL))
    {
        return false;
    }

    // Initialize cURL for making HTTP requests
    $curlInit = curl_init($domain);
    curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
    curl_setopt($curlInit,CURLOPT_HEADER,true);
    curl_setopt($curlInit,CURLOPT_NOBODY,true);
    curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

    // Get response from the server
    $response = curl_exec($curlInit);

    curl_close($curlInit);

    // If response exists, domain is available
    if ($response) return true;

    return false;
}

?>

For more information on this topic, you can refer to: https://css-tricks.com/snippets/php/check-if-website-is-available/

Answer №2

If you want to verify whether w3.css is functioning properly, you can execute a test similar to this one. Instead of "src", insert the URL for the w3.css image or any other logo.

function confirmImage (src, success, failure) {
    var imageCheck = new Image();
    imageCheck.onload = success; 
    imageCheck.onerror = failure;
    imageCheck.src = src;
}

confirmImage( "https://www.example.com/path/to/w3css/logo.png", function(){ alert("Success"); }, function(){ alert("Failure"); } );

Answer №3

Have you considered using JavaScript in this way?

<script type="text/javascript>
$.each(document.styleSheets, function(i,sheet){
  if(sheet.href=='http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css') {
    var rules = sheet.rules ? sheet.rules : sheet.cssRules;
    if (rules.length == 0) {
      $('<link rel="stylesheet" type="text/css" href="path/to/local/jquery.mobile-1.0b3.min.css" />').appendTo('head');
    }
 }
})
</script>

$.each(document.styleSheets) loops through the styleSheets of the document. For more information, visit https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets.

We then specifically verify if

http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css
is accessible. Using the ternary operator
var rules = sheet.ruless ? sheet.rules : sheet.cssRules;
, where rules becomes sheet.rules if true or sheet.cssRules if false.

Lastly, we confirm if there are contents in rules. If not, we resort to our local stylesheet solution and include it in the <head></head> section of the document.

It's important to note that issues may arise when utilizing a slow-loading CDN. An alternative could be implementing the onerror event.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simple steps for importing JS files in a web application

Upon examining the code snippet below: const express = require('express'); const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const cors = require('cors'); app.u ...

The layout of an Angular Material page gets disrupted when a sticky "header" with md-select options is used in combination with the md-backdrop

I designed a filter bar for a table that sticks above the table at a certain height. Everything was working smoothly until I opened the dropdown options in the md-select. This caused the md-backdrop to appear and apply inline positioning to the body, shift ...

Tips for Altering Information within a Text Box

Below is a snippet of HTML code that needs to be modified: <td class="targetTD"> <a href="http://foo.com"> <span>content</span> </a> **Text I want to modify** <span>more content</span> </td> The ...

A guide on incorporating dynamic information into JSON files with PHP

I am currently working on developing a checkbox tree where I require dynamic values for checkboxes. Below is my code snippet. Initially, I have static data in JSON format and now I need to retrieve dynamic data from a MySQL database. Despite trying vario ...

Changing the data type of an integer to a string within an Object

I'm working with two arrays of objects. I need to convert the data values in the first format from integers to strings, but I'm struggling to find a simple solution. Is there anyone who can provide assistance? https://i.sstatic.net/mzqWE.png If ...

Issue with flickering scroll-snap in React component with useState

I've encountered an unusual flickering glitch that only occurs when using the combination of: css scroll-snap useState Sub-Components But it's strange because the issue only arises when these three are combined! https://i.sstatic.net/TvwyW.gif ...

The hover effect is functional on the majority of browsers, with the exception of Safari and Chrome on a Mac computer

Within my html code, there are various tiles containing two images (one in jpg format as the background and one in png with transparency as the foreground) along with a hover effect: When hovering over a tile, the image zooms in towards the position of the ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

What are some ways to create a larger-than-life mui button size?

The current MUI button supports size prop values as the following small medium large Although this feature is handy, I find myself wishing I could specify the height and width using the style prop to customize the size like <Button v ...

How to use PHP for setting up a MySQL database?

Currently, I am immersing myself in the world of PHP and MySQL. I decided to take a shot at creating a basic HTML form along with a PHP script to set up a MySQL database. Unfortunately, when I tried to test it out, things didn't go as planned. Upon su ...

What is the method for retrieving the current value of a BehaviorSubject just once?

I am attempting to retrieve the current value of a BehaviorSubject without directly subscribing to it in order to avoid real-time changes reflecting immediately due to a specific requirement. My approach involves using the getValue() method. Here is an ex ...

Safari's CSS Hacking Problem

After testing the code below, it appears to be working on both Safari and Chrome. I am seeking a hack specifically for Safari, not Chrome .contactDiv img:not(:root:root) { margin-top:-75px; } @media screen and (-webkit-min-device-pixel-ratio:0) { ...

Using Flask and jQuery to dynamically load a new template once a thread has completed running

As a newcomer to Flask, I am in need of assistance. I am working on a Flask project where the user uploads a file for processing, which typically takes 1 to 2 minutes. During this processing time, I want to display a "loading" HTML page that will be replac ...

Activate mouseover function automatically for each feature on the leaflet

I'm facing a challenging situation where I need to develop a dashboard application that is similar to the functionality of ChoroplethExample. However, the catch is that I have to loop through all states (Features in geoJSON) and pause for 3 seconds at ...

Execute JavaScript with URL parameters prior to finishing Page load

I have spent hours searching for a solution, trying different methods but none of them seem to work... Here is the code snippet I am struggling with: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>&l ...

Another option for document.execCommand('selectAll',false,null)

I've come across a piece of code that allows me to select the text in a div whenever a user clicks on it: <table> <tr> <td> <div contenteditable onClick="document.execCommand('selectAll',false,null)">I& ...

In JavaScript, the handleSubmit function is effective, whereas in TypeScript React, it presents some

Currently, I am attempting to manage form submission in React using external functions and encountering an error message specific to Typescript React. Parameter 'event' implicitly has an 'any' type.ts(7006) Below is the code snippet ca ...

Changing Meteor Template to a Node.js/AngularJS Conversion

My current website is built with Meteor using templates structured like this: <body> {{>section1}} {{>section2}} {{>section3}} </body> <template name="section1"> <h1>This is Section 1</h1> </template> ...

div not recognizing the minimum height specified in percentage

I'm encountering an issue where one of my divs, content_wrap, is not adhering to the CSS property min-height:100% HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ...

Resetting clears the date default value

When the page is loaded, the date input field is automatically set to the current date. However, if the form is reset, instead of restoring the default date, the date field is cleared, as shown in the images below: Page load Form reset // app.component. ...