0.10.0 • Published 7 years ago

jquery-scopelinktags v0.10.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

jQuery ScopeLinkTags plugin

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.

Installation

npm install jquery-scopelinktags

Usage

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();

Options

The scopeLinkTags() method optionally accepts an object with the following parameters:

styleTagSelector

Type: String (Default: 'style')
Can be used to change the selector used to find the <style> tags.

cssLinkSelector

Type: String (Default: 'link[type="text/css"]')
Can be used to change the selector used to find the <link> tags.

cssRuleRegex

Type: Regex
Can be used to change the Regex that is used to detect each separate CSS selector.

useScopedStyle

Type: Boolean (Default: true)
Define whether scoped <style> tags may be used when supported.

useParentElementID

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.

scopeCssSelector

Type: String
Explicitly defines the parent CSS selector to be used for scoping.

Methods

destroy

You can revert the effects by using the destroy method:

$('body').scopeLinkTags('destroy');

scopeCss(css, scopeSelector, cssRuleRegex)

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');

Notes

  • In case that the browser natively supports <style scoped>, it will be used to scope the <link> tag CSS. Can be disabled using the useScopedStyle 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).

Limitations

  • 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