user6604655 user6604655 - 10 months ago 55
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.


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.