77 lines
2.2 KiB
JavaScript
77 lines
2.2 KiB
JavaScript
/* jshint node: true */
|
|
'use strict';
|
|
|
|
/**
|
|
# defaultcss
|
|
|
|
A very simple module for creating a little bit of defaultcss. This is
|
|
really useful if you are creating a small JS widget that you want to be
|
|
completely stylable by the application implementer but would also like it
|
|
to look "kind of ok" if someone want to have a quick play.
|
|
|
|
## How it Works
|
|
|
|
The provided css text is injected into the HTML document within the document
|
|
`<head>` prior to any other `<link>` or `<style>` tags. This ensures that
|
|
any definitions that are made within your provided CSS have ample
|
|
opportunity to be overridden by user defined CSS.
|
|
|
|
## Example Usage
|
|
|
|
<<< examples/widget.js
|
|
|
|
## Reference
|
|
|
|
### defaultcss
|
|
|
|
```
|
|
defaultcss(label, csstext)
|
|
```
|
|
|
|
Create a new default `style` element and use the provided `label` to
|
|
generate an id for the element "%label%_defaultstyle". If an existing
|
|
element with that id is found, then do nothing.
|
|
|
|
If not, then create the new element and use the provided `csstext` as
|
|
`innerText` for th element.
|
|
**/
|
|
module.exports = function(label, text) {
|
|
var styleId = label + '_defaultstyle';
|
|
|
|
// look for a DOM element with the style id
|
|
var styleEl = document.getElementById(styleId);
|
|
|
|
// find the first <link> or <style> tag within the document head
|
|
var firstStyleDef = document.querySelector('link[rel="stylesheet"],style');
|
|
|
|
// if we can find a DOM element with that id, then do nothing as a default
|
|
// style has already been applied
|
|
if (styleEl) {
|
|
return styleEl;
|
|
}
|
|
|
|
// otherwise, create a style element
|
|
styleEl = document.createElement('style');
|
|
styleEl.innerHTML = text;
|
|
|
|
// insert the style element, in order or preference
|
|
// 1. before the first style related element in the page
|
|
if (firstStyleDef) {
|
|
firstStyleDef.parentNode.insertBefore(styleEl, firstStyleDef);
|
|
}
|
|
// 2. to the end of the HEAD
|
|
else if (document.head) {
|
|
document.head.appendChild(styleEl);
|
|
}
|
|
// 3. as the first element in the body
|
|
else if (document.body && document.body.childNodes.length > 0) {
|
|
document.body.insertBefore(styleEl, document.body.childNodes[0]);
|
|
}
|
|
// 4. in the body
|
|
else if (document.body) {
|
|
document.body.appendChild(styleEl);
|
|
}
|
|
|
|
return styleEl;
|
|
};
|