简体   繁体   English

如何使用Javascript从CDN加载和外部CSS文件?

[英]How to load and external css file from the CDN with 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. 简要地讲,我想将引导css文件加载到Internet上的网页上(而不是在我的网站上),以便在浏览器控制台中使用Javascript对其进行一些自定义。

I tried to load bootstrap from the CDN using jQuery like this: 我试图使用jQuery从CDN加载引导程序,如下所示:

$("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 ? 如何将其成功加载到页面?

From js standpoint your approach is right. 从js的角度来看,您的方法是正确的。 You tried to load a script from another site and, because you've restricted this by Content Security Policy (CSP), you can't. 您试图从另一个站点加载脚本,并且由于受内容安全策略(CSP)的限制,您不能这样做。 Check your CSP metatag. 检查您的CSP元标记。

I suggest you to read more about it in this MDN article. 我建议您在此MDN文章中阅读更多有关它的内容。

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") 

Here you go: 干得好:

var mySheet = document.createElement('link');mySheet.type='text/css';mySheet.rel='stylesheet';mySheet.href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css';document.getElementsByTagName('head')[0].appendChild(mySheet);

Paste above code in DevTools -> console, hit Enter and you're good to go. 将上述代码粘贴到DevTools->控制台中,按Enter键,一切顺利。

The main point here is to create HTML tag at first, fill it up with properties and add it to the DOM's 这里的要点是首先创建HTML标记,将其填充属性,然后将其添加到DOM的

This worked for me: 这为我工作:

var head = document.head;
var link = document.createElement('link');



link.type = 'text/css';


link.rel = 'stylesheet';


link.href = fileName/url;



head.appendChild(link);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM