如何使用Javascript从CDN加载和外部CSS文件? [英] How to load and external css file from the CDN with Javascript?
问题描述
简而言之,我想将引导css文件加载到网页上在互联网上(而不是在我的网站上),使用浏览器控制台中的Javascript在互联网上进行一些自定义.
briefly, I want to load the bootstrap css file on a web page on the internet (not on my website), to do some customization on it using Javascript in the browser console.
我试图使用jQuery这样从CDN加载引导程序:
I tried to load bootstrap from the CDN using jQuery like this:
$("head").append("<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' type='text/css' />");
这样做时,我会收到以下错误消息:
When doing that I get this error message:
如何成功将其加载到页面上?
What should I do to load it successfully to the page ?
推荐答案
从js的角度来看,您的方法是正确的.您试图从另一个站点加载脚本,并且由于受内容安全策略(CSP)的限制,您不能这样做.检查您的CSP元标记.
From js standpoint your approach is right. You tried to load a script from another site and, because you've restricted this by Content Security Policy (CSP), you can't. Check your CSP metatag.
我建议您阅读有关此内容的更多信息在此MDN文章中.
I suggest you to read more about it in this MDN article.
要简单地允许所有仅在错误仍然出现时进行测试,您可以使用以下方法:
To simply allow all just for test if error still appears, you can use this:
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'">
检查此答案,并详细说明此标签的工作原理
Check this answer with detail explanation of how this tag works
顺便说一句,这对我有用:
BTW, this works for me:
function loadCss(filename) {
var cssNode = document.createElement("link");
cssNode.setAttribute("rel", "stylesheet");
cssNode.setAttribute("type", "text/css");
cssNode.setAttribute("href", filename);
document.getElementsByTagName("head")[0].appendChild(cssNode);
}
loadCss("//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css")
这篇关于如何使用Javascript从CDN加载和外部CSS文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!