0

In my javascript app, I dynamically add css to a page, using something like this

document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="/components/bubble_list/simple/sm_bubble_list.css">';

I'm not sure if this is me, but I find that it seems to temporarily disable all existing css when processing the css from that file. If this is the normal behaviour, is there a better way to add css dynamically, so that the flow is more natural, like it only processes the css from that file?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

3 Answers3

0

Try this

var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', '/components/bubble_list/simple/sm_bubble_list.css');
document.getElementsByTagName('head')[0].appendChild(link)
McMyt
  • 95
  • 1
  • 3
  • 7
0

If css file:

var link = document.createElement('link')
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
link.setAttribute('href', 'css/my.css')
document.getElementsByTagName('head')[0].appendChild(link)

If css text:

var style = document.createElement('style')
style.type = 'text/css'
style.innerHTML = 'content'
document.getElementsByTagName('head')[0].appendChild(style)
0

If you want to link CSS File

change css/style.css to your path to your css link

// var css link
var csslink = document.createElement('link')
// set attribute to css link file
csslink.setAttribute('rel', 'stylesheet')
csslink.setAttribute('type', 'text/css')
csslink.setAttribute('href', 'css/style.css') // change css/style.css to the path of your css link
document.getElementsByTagName('head')[0].appendChild(link)
Esam Eisa
  • 9
  • 1
  • 7