This plugin provides a way to scope CSS <link>
tags inside their container, similarly to the way that scoped <style>
tags work.
Initially inspired by this stackoverflow response and thingsinjars/jQuery-Scoped-CSS-plugin.
Note: you should only have to use this approach in case that you can't control the imported CSS file. If you can use SASS/LESS/anything to pre-process your CSS, you should prefer that.
npm install jquery-scopelinktags
Include this plugin's source and on $(document).ready()
call:
// scope all <link> tags inside of the <body>
$('body').scopeLinkTags();
// OR specifically define the scoped section/container
$('.scoped-section').scopeLinkTags();
// OR even target specific <link> tags with your own custom selector
$('link[data-scoped]').scopeLinkTags();
The scopeLinkTags()
method optionally accepts an object with the following parameters:
Type: String (Default: 'style'
)
Can be used to change the selector used to find the <style>
tags.
Type: String (Default: 'link[type="text/css"]'
)
Can be used to change the selector used to find the <link>
tags.
Type: Regex
Can be used to change the Regex that is used to detect each separate CSS selector.
Type: Boolean (Default: true
)
Define whether scoped <style>
tags may be used when supported.
Type: Boolean (Default: true
)
Define whether the ID of the <link>
parent element may be used when available. Otherwise a new unique [class]
will be generated and used for each <link>
tag.
Type: String
Explicitly defines the parent CSS selector to be used for scoping.
You can revert the effects by using the destroy
method:
$('body').scopeLinkTags('destroy');
The method that scopes the CSS rules is globally available:
var myCss = "p { color: blue; }";
var scopedCss = $.fn.scopeLinkTags.scopeCss(myCss, '.myScopedBlueArea');
The jQuery plugin instance can be rertieved from the generated <style>
tag with:
var instance $('.scopedArea > style').data('scopeLinkTags');
- In case that the browser natively supports
<style scoped>
, it will be used to scope the<link>
tag CSS. Can be disabled using theuseScopedStyle
option. - When
<style scoped>
is not supported, the plugin will use the[id]
of the container element, or a newly created unique[class]
, as a parent selector for the CSS rules detected (using a REGEX replace).
- Only
<link>
tags that have the[type="text/css"]
attribute will be processed. - Does not apply to externally loaded stylesheets (via @import).
- When wrapping the detected CSS with a parent CSS selector
- Expect to work on valid CSS, even when minified.
- Please open a ticket if you find a case that the used REGEX doesn't work