gpt4 book ai didi

javascript - 从 CDN 为 CSS 提供本地回退

转载 作者:技术小花猫 更新时间:2023-10-29 11:40:40 25 4
gpt4 key购买 nike

我正在从 CDN bootstrapcdn.com 在我的页面上加载 Bootstrap CSS

<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">

如何测试样式表是否已加载,如果未加载则提供本地回退?

不想在进行测试之前等待 jQuery 或其他库加载;我希望所有 CSS 首先加载到页面上。

最佳答案

这是我为满足我们的需要而创建的。如果这满足您的需要,只需调用函数 ensureCssFileInclusion(file to check, boolean value)。您必须根据需要调整它,以确保在此函数中提供 cssFileToCheck、fallbackCssFile。

/**
* Checks the page for given CSS file name to see if it was already included within page stylesheets.
* If it was, then this function does nothing else. If CSS file was not found among page stylesheets,
* then this function will attempt to load the stylesheet by adding an HTML link tag to the document
* HEAD section. You must also specify whether given cssFileToInclude is a relative path or an absolute path.
*/
ensureCssFileInclusion = function(cssFileToInclude, isRelativePath) {
if (isRelativePath) {
if (!window.location.origin) {
cssFileToInclude = window.location.protocol+"//"+window.location.host + cssFileToInclude;
}
}
var styleSheets = document.styleSheets;
for (var i = 0, max = styleSheets.length; i < max; i++) {
if (styleSheets[i].href == cssFileToInclude) {
return;
}
}
// because no matching stylesheets were found, we will add a new HTML link element to the HEAD section of the page.
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = cssFileToInclude;
document.getElementsByTagName("head")[0].appendChild(link);
};

关于javascript - 从 CDN 为 CSS 提供本地回退,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17437199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com