[英]add javascripts and css files dynamicly to html using javascript
I am building a javascript widget and i need to add my widget css and js files dynamicly to the client page. 我正在构建一个JavaScript小部件,我需要将小部件的CSS和JS文件动态添加到客户端页面。
I am doing this for now: 我现在正在这样做:
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', 'css path');
document.getElementById('test').appendChild(css);
alert(document.getElementById('test').innerHTML);
But it does not add the element to the dom. 但这不会将元素添加到dom中。 The alert shows correctly. 警报显示正确。
What i am missing? 我想念什么?
EDIT1: 编辑1:
Here is the updated code: (note that this is only a test page). 这是更新的代码:(请注意,这只是一个测试页)。
<html>
<head>
</head>
<body>
<div id="test">
test
</div>
<script type="text/javascript">
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute("type", "text/css");
css.setAttribute('href', 'path');
var header = document.getElementsByTagName("head")[0];
header.appendChild(css);
alert(header.innerHTML);
</script>
</body>
</html>
header.InnerHtml appears correct but nothing is added to the page. header.InnerHtml看起来正确,但是没有任何内容添加到页面。
have you tried to append the css into the <head> section ? 您是否尝试将CSS附加到<head>部分?
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', 'css path');
document.getElementsByTagName('head')[0].appendChild(css);
I think you need to attach it to the of your html, not simply the document: 我认为您需要将其附加到您的html上,而不仅仅是文档:
var css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute("type", "text/css");
css.setAttribute('href', 'css path');
var header = document.getElementsByTagName("head")[0];
header.appendChild(css);
Hope this helps :) 希望这可以帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.