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.
Asked
Active
Viewed 86 times
0
-
do you use any kind of server scripting ? – Marko Mackic Jul 28 '16 at 21:20
-
2An included JS file can add a CSS link when it runs. – nnnnnn Jul 28 '16 at 21:20
-
or as @nnnnnn said, but if answer to first question is yes ,you could inject them into file before it's downloaded, then you get all files at cost of 1 request – Marko Mackic Jul 28 '16 at 21:21
-
@nnnnnn – But that may affect the layout... – Rayon Jul 28 '16 at 21:21
-
An `include()` php function will do. Make a separate php file containing the js and css refs and call it on the head of your html. (no php tag included though, just an idea..... :v ) – Cookie Ninja Jul 28 '16 at 21:22
-
@Rayon - Even if included in the ``? Either way, I'm not aware of another way to do it. (I don't see how server-side stuff could help for "downstream consumers".) – nnnnnn Jul 28 '16 at 21:23
-
@nnnnnn you take the contents of the css file (that file must contain css inside – Marko Mackic Jul 28 '16 at 21:24
-
@MarkoMackic - Well yes, but I don't think that's "simplified" for downstream consumers, because it forces them to use some server-side coding on their page rather than using a simple html-based include, and that may not be possible for some users. – nnnnnn Jul 28 '16 at 21:27
-
Is there any type of tool or automated build task that can take a js file and a css file and concatenate them together into a single js file or some other relevant modern file type that would be usable for this type of implementation? This would further simplify the downstream client implementation. – user6604655 Jul 28 '16 at 21:37
2 Answers
3
One possible way would be to include only the JavaScript, and within it, to load your CSS.
Take a look here: How to load up CSS files using Javascript?

Community
- 1
- 1

Stayko Dimitrov
- 87
- 5
0
You can include your CSS as a string in your JavaScript:
var myStylesheet =
'body { background-color: blue; }
#my-div{ background-color: white; }'
;
Then:
var styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.innerHTML = myStylesheet;
document.head.appendChild(styleElement);
This creates a style element and places it in the document head.
It is equivalent to:
<head>
...
<style type="text/css">
body { background-color: blue; }
#myDiv { background-color: white; }
</style>
</head>
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.

A. Vidor
- 2,502
- 1
- 16
- 24