user6604655 user6604655 - 1 year ago 94
Javascript Question

any way to include js ref and css ref as a single ref?

Do you know if there's a way to include a js ref and css ref as a single ref in html? Normally these refs are included separately in the html head but my manager wants to know if there's a simplified way for downstream consumers to add these refs as a single ref.

Answer Source

You can include your CSS as a string in your JavaScript:

var myStylesheet = 
  'body { background-color: blue; }
   #my-div{ background-color: white; }'


var styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.innerHTML = myStylesheet;

This creates a style element and places it in the document head.

It is equivalent to:

  <style type="text/css">
    body { background-color: blue; }
    #myDiv { background-color: white; }

This is the bundling approach used by, for example, the dat.gui library; see, for example, the inject function defined at line 42 of the un-minified build, and the (very lengthy!) style string at line 2857.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download