How to load and external css file from the CDN with Javascript?

核能气质少年 提交于 2019-12-11 06:18:43

问题


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.

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 ?


回答1:


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.

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



回答2:


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



回答3:


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.

The main point here is to create HTML tag at first, fill it up with properties and add it to the DOM's



来源:https://stackoverflow.com/questions/45980072/how-to-load-and-external-css-file-from-the-cdn-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!