Martin
Martin

Reputation: 11336

Include external CSS when rendering HTML inside javascript

I'm creating a tool that display a banner on a website when a simple javascript line is placed. Something like this is enough to show the banner on any page.

<script type="text/javascript" src="http://mysite.com/mytool/"></script>

Basically its code is something like this

var div = document.createElement('div')
document.write('<div>all content goes here</div>');

Since its a 300 line app there is a lot of CSS involved.

Is there any way to embed an external CSS file when doing this inline HTML rendering via javascript?

I'm not using jQuery or any other library since I'm trying to reduce the output size as possible as I can.

Upvotes: 0

Views: 112

Answers (2)

Wouter J
Wouter J

Reputation: 41934

You can print the link tag, as @Pointy pointed out:

document.write('<link href=stylesheet href=foo/style.css>');

But better is to place it in the head:

document.head.innerHTML += '<link href=stylesheet href=foo/style.css>';

Upvotes: 4

Rab
Rab

Reputation: 35572

head = document.getElementsByTagName('head')[0],
style = document.createElement('link');
style.type = 'text/css';
style.href = "pathtocss.css"
style.rel = "stylesheet"
head.appendChild(style);

Upvotes: 3

Related Questions