kubetail-org / sentineljs Goto Github PK
View Code? Open in Web Editor NEWDetect new DOM nodes using CSS selectors (650 bytes)
License: MIT License
Detect new DOM nodes using CSS selectors (650 bytes)
License: MIT License
Can you please explain extraAnimation
a little bit more? I'm scratching my head about it..
Sentinel is loading elements in backwards order.
This is DOM
<div>div</div>
<span>span</span>
<strong>strong</strong>
This is JavaScript
sentinel.on('div', function(el) {
console.log(el)
});
sentinel.on('span', function(el) {
console.log(el)
});
sentinel.on('strong', function(el) {
console.log(el)
});
This is the console log
<strong>strong</strong>
<div>div</div>
<span>span</span>
For a better example of this behavior please look at this demo on jsfiddle
Tests:
If you make script run at execution time you will see that Safari ignores all markup on DOM at hard refresh.
If you make script run only on Window Load event Safari ignores all markup on DOM at execution time.
If you make script run only on Document readystatechange event Safari ignores all markup on DOM on hard refresh.
If you make script run only on Window DOMContentLoaded event all 3 browsers ignore markup on DOM at execution time.
Code:
Editor mode - https://codepen.io/petermonte/pen/Vwwqgjv?editors=0010
Debug mode - https://cdpn.io/petermonte/debug/Vwwqgjv/PNrvYXGWZBPM
Specs:
Screen recordings:
https://user-images.githubusercontent.com/4997381/106580084-652e3380-6539-11eb-8137-9ffea143c4ec.mov
https://user-images.githubusercontent.com/4997381/106580430-d0780580-6539-11eb-8b80-d9ce14444d18.mov
This is a request by @amorey in #8 (comment)
🚨 You need to enable Continuous Integration on Greenkeeper branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet.
We recommend using:
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please click the 'fix repo' button on account.greenkeeper.io.
Omit the name and time stamp from the gzip file with gzip --no-name
to save a handful of bytes (thirteen).
Save another three bytes by removing the trailing semicolon and EOL.
This takes it down from 682 to 666 bytes.
I was then able to save another 77 bytes (to 589 bytes, >13%) before I decided that I was really spending too much time on this. Golfing gzipped minified JavaScript size seems to be a hobby of mine.
Do whatever you like (nothing or anything) with this JavaScript which should be functional but is completely untested:
sentinel = (function (document, isArray) {
var selectorToAnimationMap = {};
var animationCallbacks = {};
var styleEl;
var styleSheet;
var cssRules;
return this.sentinel || {
on: function (cssSelectors, callback, extraAnimations) {
if (!callback) return;
// initialize animationstart event listener
if (!styleEl) {
// add animationstart event listener
['animationstart', 'mozAnimationStart', 'webkitAnimationStart'].map(function(event) {
document.addEventListener(event, function (ev) {
var callbacks = animationCallbacks[ev.animationName] || [];
var l = callbacks.length;
var i = 0;
if (!l) ev.stopImmediatePropagation();
for (; i < l; i++) callbacks[i](ev.target);
}, true);
});
// add stylesheet to document
styleEl = document.createElement('style');
document.head.appendChild(styleEl);
styleSheet = styleEl.sheet;
cssRules = styleSheet.cssRules;
}
// listify argument
(isArray(cssSelectors) ? cssSelectors : [cssSelectors])
// add css rules and cache callbacks
.map(function(selector) {
var animId = selectorToAnimationMap[selector];
if (!(animId)) {
// add new CSS listener
// add keyframe rule
cssRules[styleSheet.insertRule(
'@keyframes ' + (selectorToAnimationMap[selector] = animId = 'sentinel-' + Math.random().toString(16).slice(2)) + '{from{transform:none}to{transform:none}}',
cssRules.length
)]._id =
// add selector animation rule
cssRules[styleSheet.insertRule(
selector + '{animation-duration:0.0001s;animation-name:' + animId + (extraAnimations ? ',' + extraAnimations : '') + '}',
cssRules.length
)]._id = selector;
}
// add to callbacks
(animationCallbacks[animId] = animationCallbacks[animId] || []).push(callback)
});
},
off: function(cssSelectors, callback) {
// listify argument
(isArray(cssSelectors) ? cssSelectors : [cssSelectors])
// iterate through rules
.map(function(selector, animId) {
// get animId
if (!(animId = selectorToAnimationMap[selector])) return;
// get callbacks
var callbackList = animationCallbacks[animId]||[];
var i = callbackList.length;
// remove callback from list
if (callback) {
while (i--) {
if (callbackList[i] === callback) callbackList.splice(i, 1);
}
}
// exit if callbacks still exist
if (callbackList.length) return;
// clear cache and remove css rules
i = cssRules.length;
while (i--) {
if (cssRules[i]._id == selector) styleSheet.deleteRule(i);
}
delete selectorToAnimationMap[selector];
delete animationCallbacks[animId];
});
},
reset: function(p) {
selectorToAnimationMap = {};
animationCallbacks = {};
styleEl && styleEl.parentNode.removeChild(styleEl);
styleEl=0;
}
};
})(document, Array.isArray);
Mostly I retained the semantics exactly, but I made a few changes:
document._sentinelJS
which I don’t think was doing what you wanted (it would make sentinel
undefined);All up, I’m at 589 bytes.
After I decided to stop I then remembered that you’re using mozAnimationStart
and webkitAnimationStart
, but without @-moz-keyframes
and @-webkit-keyframes
they’re useless. If you care about compatibility, add the prefixed keyframes, if you care about size, remove the prefixed event names.
This is a super neat technique. Except when the DOM element has animation-name
rule defined, it stops working.
Hi Everyone,
I just wanted to let you know that there's a new release of SentinelJS that includes support for triggering watch functions from CSS using custom animation event names (v0.0.4):
<style>
@keyframes slidein {
from: {margin-left: 100%;}
to: {margin-left: 0%;}
}
.my-div {
animation-duration: 3s;
animation-name: slide-in, node-inserted;
}
</style>
<script>
// trigger on "node-inserted" animation event name (using "!" prefix)
sentinel.on('!node-inserted', function(el) {
el.insertHTML = 'The sentinel is always watching.';
});
</script>
This feature is useful when you want to trigger multiple animation events using the same CSS selector. Here's a demo of the new feature:
https://jsfiddle.net/muicss/25nus53b/
Special thanks to @chris-morgan and @tnhu for help with decreasing the payload size and identifying the animation issue!
Andres
I have come up with a simple alternative strategy that allows Sentinel to not conflict with previously defined animations: Just add a data attribute after the event fires and then make the animation use a negative attribute selector.
CSS
.some.selector.you.are.watching:not([data-sentinal-watched]) {
animation: 0.0001s sentinal_watch;
}
Javascript
document.addEventListener('animationstart', ev => {
if(ev.animationName === 'sentinal_watch') {
ev.target.setAttribute('data-sentinal-watched', '');
}
});
Link to a CodePen example: https://codepen.io/danielbodart/pen/MWyxNQY
I don't think it's perfect as you will probably have a flicker as the JS will take time to run but maybe it's better?
Per w3c/csswg-drafts#1594, the CSS WG is amenable to making animations composable/additive: either via a general-purpose !add
annotation, or via an animation-composite
property. The adoption and implementation of such functionality would remove the need for manually specifying the animation-name
of an animation already attached to the desired element(s).
Our particular use-case for this feature is to interoperate with third-party pages from browser extensions without breaking animations the page may be using, and without hardcoding the animations the page already uses.
I'm using the Sentinel.js to initialise several components and functionalities on the DOM.
Most of these components get to use plenty of css and js functionalities by using classnames or attributes. It seems that some of them get ignored or overwritten.
I've created a demo to show this behaviour: https://codepen.io/petermonte/pen/XWWKRNv?editors=0010
HTML
<h1 id="h1" class="h1" data-h1="dataset">This is an Heading 1</h1>
CSS
h1[data-underline="true"] {
text-decoration: underline;
}
JS
// By classname
sentinel.on('.h1', function(el) {
// BECOMES BLUE
el.style.color = 'blue';
});
// By node name
sentinel.on('h1', function(el) {
// CHANGES TEXT TO: This is an Heading 1 + H1
el.textContent += ' + ' + el.nodeName;
});
// By ID
sentinel.on('#h1', function(el) {
// CHANGES TEXT TO: This is an Heading 1 + H1 + h1
el.textContent += ' + ' + el.id;
});
// By data attribute
sentinel.on('[data-h1]', function(el) {
// MAKES TEXT UNDERLINED
el.dataset.underline = true;
});
the idea is that all calls should run adding up all the changes to the element. Play arround by commenting all js sentinel calls and see how the element only reacts the a single call.
Hi, thanks for creating this awesome library.
I use sentineljs
in userscript to monitor elements on the page. But the style injected by sentineljs
will be blown away by things like next/head
.(ref)
I would like to know why it uses insertBefore
to inject the style to the start of head
.
By adopting this change can fix the problem I mentioned.
// add stylesheet to document
styleEl = doc.createElement('style');
- head.insertBefore(styleEl, head.firstChild);
+ head.append(styleEl);
styleSheet = styleEl.sheet;
cssRules = styleSheet.cssRules;
I understand that asking the library to adapt to this specific usecase might be weird. Please let me know what you think. 🙏
A good point to warn people on the documentation is that any element that has its default property display
to none
will not get called under Sentinels watch. Unless there is a css property to watch, that even with no rendering or display, it gets listed under the transitionend
event.
here is an example of the display:none
impact: https://codepen.io/petermonte/pen/LYPKKQQ
Hey, clever library! I was looking for something like this to facilitate sharing components between JS SPAs and WordPress sites.
May I suggest a paragraph in the readme that explains how it works and whether there are any tradeoffs? I figured it out from the source but it would have been great to see a sentence or two summarizing it.
Did you consider using a mutation observer to detect new elements instead of animate events? Looks like this has slightly more browser support but mutation observer is pretty good.
Hi, maybe this is a very newbie question but,
In your dist version you have this code to dispatch the event
// dispatch load event
ev = doc.createEvent('HTMLEvents');
ev.initEvent('sentinel-load', false, false);
doc.dispatchEvent(ev);``
But where is it in the src version?
How did you get that? I'm trying to understand it but i can't 😢
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.