Intersection Observer: Call a function only once per element - javascript

I'm using the Intersection Observer API to track the visibility of multiple element on a web page. When an element becomes visible, a function callback() should be executed. The restriction: For each element, the function may only be executed once.
Here is my current implementation for a web analytics project:
const elements = document.querySelectorAll('[data-observable]');
const callback = str => { console.log(str); };
const observer = new IntersectionObserver(handleIntersection);
elements.forEach(obs => {
observer.observe(obs);
});
function handleIntersection(entries, observer){
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
// Call this function only once per element, without modifying entry object
callback('observer-' + entry.target.getAttribute('data-observable'));
}
});
}
I'm struggeling to find a solution that does not modify existing elements, the IntersectionObserver or the IntersectionObserverEntries.
Usually I would use a closure to ensure that a function gets only executed once:
function once(func) {
let executed = false;
return function() {
if (!executed) {
executed = true;
return func.apply(this, arguments);
}
};
}
But in this case I have difficulties applying the function because IntersectionObserver uses a weird callback iterator logic that get's executed everytime any element changes (instead of using a event-driven model).
Any ideas, how to implement a once per element function call that does not mutate other elements or objects?

As James pointed out in the comments, the easiest solution to this problem is unobserving the element once it has become visible and the callback has been invoked.
const elements = document.querySelectorAll('[data-observable]');
const callback = str => { console.log(str); };
const observer = new IntersectionObserver(handleIntersection);
elements.forEach(obs => {
observer.observe(obs);
});
function handleIntersection(entries, observer){
entries.forEach(entry => {
if (entry.intersectionRatio > 0) {
callback('observer-' + entry.target.getAttribute('data-observable'));
observer.unobserve(entry.target);
}
});
}
I didn't find any viable solution to use a closure to control how often a function can be called.

Related

How to create a loop that can be programatically iterated when inner callback is executed?

I am iterating over an array of assets, I need to load each of these assets to gpu (using third party library for this). Loader provided by such third party library has a callback function that is executed when asset is loaded i.e. right now I have something like this
assetsArr.forEach(asset => {
myLoader.upload(asset, () => {
// Go to next loop / iteration here
})
});
Since this callback is not executed right away I am currently in a situation where my loop finishes before my assets are actually loaded leading to some issues in my app.
Is there a way to loop over assetsArr, but only go to next iteration / loop once that callback is executed?
You could do this by wrapping myLoader in a Promise. As I dont have the code for myLoader I'll simulate it with a delay which just waits a few seconds.
async function dummyUpload(asset){
return new Promise(resolve => {
console.log("dummyUpload",asset);
setTimeout(resolve,3000);
});
}
async function test(assets){
for(var i=0;i<assets.length;i++){
var asset = assets[i];
console.log("starting",asset);
await dummyUpload(asset);
console.log("finished",asset);
};
}
var assets = [1,2,3];
test(assets);
The way to wrap your upload function is fairly simple:
async function loaderFunction(asset){
return new Promise( resolve => {
myLoader.upload(asset, resolve);
});
}
You may also want to check if your "loader" supports a Promise-based interface which would be better than wrapping in another Promise.
Create function loader like below and call it with loader(assetsArr, 0);. Inside callback function at the end add code index++; and check if (index < assetsArr.length) then loader(assetsArr, index);.
Test it below. For testing I have added custom code for myLoader.
let myLoader = {
upload : (asset, callback) => setTimeout(callback, 1000)
};
let assetsArr = [1, 2, 3];
function loader(assetsArr, index) {
let asset = assetsArr[index];
myLoader.upload(asset, () => {
console.log(index);
// Go to next loop / iteration here
index++;
if (index < assetsArr.length) {
loader(assetsArr, index);
}
})
}
loader(assetsArr, 0);

Invoke and return a function

Is there a way to do this in JS
function namedFunction(elements,args) {
const domElements = document.querySelector(elements);
const initialValue = 0;
let incrementBy = 5;
return function() {
// Do something to domElements based on initialValue and incrementBy
// function needs to run the first time namedFunction is called
// and this is the only function that needs to run on subsequent calls to namedFunction
}.call(null)
// the .call does not work as intended here, but this is basically what I want to do.
}
I think I can do namedFunction()() with the code above in order to invoke both, but I'm wondering if there is another way.
The longer version of the function would look like this:
function namedFunction(elements,args) {
const domElements = document.querySelector(elements);
const initialValue = 0;
let incrementBy = 5;
function namedFunctionEventHandler() {
// Do something to domElements based on initialValue and incrementBy
// function needs to run the first time namedFunction is called
// and this is the only function that needs to run on subsequent calls to namedFunction
}
namedFunctionEventHandler();
return namedFunctionEventHandler;
}
The goal would be to pass a single function as an event handler, that the first time it runs it does initial calculations, caches dom elements and the more heavier stuff, then executes the logic that is abstracted in the returned function and on subsequent calls it uses the data from the closure.
Edit: the namedFunction does not need to accept any arguments, its just for demonstration purposes.
document.addEventListener('scroll', namedFunction)
is what I want to be able to do.
#CertainPerformance - Sorry, I misread your answer.
If you take a look at the end result I would like to achieve, your proposition wont actually work as intended, as if I pass an invoked function as an event handler, its gonna run before an event has actually happened.
You can make namedFunction into an IIFE that saves a reference to a function (initially undefined). On call, if that variable is undefined, carry out the expensive calculations and then assign to the variable; if the variable is defined, then simply call it.
const handler = (() => {
let cheapFn;
return () => {
if (cheapFn) {
cheapFn();
return;
}
// expensive calculations here
const domElements = document.querySelector(elements);
...
cheapFn = () => {
// assign to cheapFn
};
cheapFn();
};
})();
Demo:
const handler = (() => {
let cheapFn;
return () => {
if (cheapFn) {
cheapFn();
return;
}
// expensive calculations here
console.log('expensive');
cheapFn = () => {
console.log('cheap');
};
cheapFn();
};
})();
document.addEventListener('scroll', handler);
body {
height: 400px;
}
body
You can take advantage of the fact that functions in JavaScript are first-class objects, and store the function state (initialized/uninitialized) in a property of the function.
The data computed during initialization can be stored in the function properties as well, please take a look at the demo:
const namedFunction = function(elements,args) {
if (!namedFunction.isInitialized) {
console.log('Initialization: Computing initial value...');
namedFunction.initialValue = 10 * 10;
console.log(`Initial value: ${namedFunction.initialValue}`);
namedFunction.isInitialized = true;
}
return function() {
console.log('Running regular operation:');
console.log(`Current value: ${--namedFunction.initialValue}`);
}.call(null)
}
document.getElementById('demo').addEventListener('click', namedFunction);
<button id="demo">Run</button>

Override JQuery functions (logging decorator)

I'd like to create a logging decorator around jQuery function but it is called only once (in initialization time). How to fix it? Please look at the code.
function makeLogging(f) {
function wrapper(...rest) {
console.log(f.name);
console.log(rest);
return f.apply(this, rest);
}
return wrapper;
}
const task = $('.task');
task.on = makeLogging(task.on);
task.on('click', () => console.log('hi'));
The click event does not display messages about the called function.
You are doing it a little bit wrong, if I caught the idea what you want to achieve. For functionality, you described, please try following:
task.on('click', makeLogging(() => console.log('hi')));
In your original code, you wrapped the functionality of on() function, but this on() function is not called as event handler - it only install actual event handler. That's why logging is called only once during installation of the handler.
Code example of answer
function makeLogging(f) {
function auxiliaryWrapper(x, rest) {
return () => {
console.log(f.name);
console.log(rest);
x();
}
}
function mainWrapper(...rest) {
const restWithWrap = rest.map(arg => {
if (typeof arg === 'function') {
return auxiliaryWrapper(arg,rest);
}
return arg;
});
console.log(restWithWrap);
return f.apply(this, restWithWrap);
}
return mainWrapper;
}
const task = $('.task');
task.on = makeLogging(task.on);
task.on('click', () => console.log('hi'));

understanding event handling and callbacks in javascript

I was messing around with IndexedDB and I realised that I don't really get event handling in JavaScript.
So here's the code:
var request = indexeddb.open(bla, version);
request.onsuccess = function (event) { };
So the open-method returns a IDBOpenDBRequest object, which, according to Mozillas site, inherits from IDBRequest, which apart from properties and methods also has event handlers, one of them being onsuccess:
https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.onsuccess
So on the mozilla site, onsuccess is just function () { }
Now, when the database was opened sucessfully, the "onsuccess" event fires and the appropiate event handler is called, in this case the function that I defined. But how exactly does that happen?
The request variable contains an instance of the IDBOpenDBRequest. So when I write request.onsuccess = somefunction(), am I overwriting the default function of the IDBRequest-class?
I dont get why I can write request.onsuccess = somefunction(event) { } and how the event is passed to that function.
EDIT:
function myObect() {
this.open = function(a,b,c) {
if (c > 20) {
this.success("String");
}
};
};
var myrequest = new myObect();
myrequest.open(4,2,21);
myrequest.success = function (ev) {
console.log(ev);
};
To create a similar api, you can do something like:
function open(a, b, c) {
var request = {};
if(c > 20) {
setTimeout(function() {
if(typeof request.success === "function") {
request.success("String");
}
}, 1);
}
return request;
}
var myrequest = open(4, 2, 21);
myrequest.success = function(ev) {
console.log(ev);
};
Here, setTimeout is asynchronous so the callback function is not executed immediately. When any asynchronous task is run in JavaScript, the currently executing code will run to completion before any callback is called. So success is guaranteed to be set before request.success called.
The Indexed DB open call similarly runs an asynchronous task, and then dispatches events when it is finished which will eventually call your callback function.
I overwriting the default function of the IDBRequest-class
Looks like there is no default behavior, so you just set up your own func.

Make function wait until element exists

I'm trying to add a canvas over another canvas – how can I make this function wait to start until the first canvas is created?
function PaintObject(brush) {
this.started = false;
// get handle of the main canvas, as a DOM object, not as a jQuery Object. Context is unfortunately not yet
// available in jquery canvas wrapper object.
var mainCanvas = $("#" + brush).get(0);
// Check if everything is ok
if (!mainCanvas) {alert("canvas undefined, does not seem to be supported by your browser");}
if (!mainCanvas.getContext) {alert('Error: canvas.getContext() undefined !');}
// Get the context for drawing in the canvas
var mainContext = mainCanvas.getContext('2d');
if (!mainContext) {alert("could not get the context for the main canvas");}
this.getMainCanvas = function () {
return mainCanvas;
}
this.getMainContext = function () {
return mainContext;
}
// Prepare a second canvas on top of the previous one, kind of second "layer" that we will use
// in order to draw elastic objects like a line, a rectangle or an ellipse we adjust using the mouse
// and that follows mouse movements
var frontCanvas = document.createElement('canvas');
frontCanvas.id = 'canvasFront';
// Add the temporary canvas as a second child of the mainCanvas parent.
mainCanvas.parentNode.appendChild(frontCanvas);
if (!frontCanvas) {
alert("frontCanvas null");
}
if (!frontCanvas.getContext) {
alert('Error: no frontCanvas.getContext!');
}
var frontContext = frontCanvas.getContext('2d');
if (!frontContext) {
alert("no TempContext null");
}
this.getFrontCanvas = function () {
return frontCanvas;
}
this.getFrontContext = function () {
return frontContext;
}
If you have access to the code that creates the canvas - simply call the function right there after the canvas is created.
If you have no access to that code (eg. If it is a 3rd party code such as google maps) then what you could do is test for the existence in an interval:
var checkExist = setInterval(function() {
if ($('#the-canvas').length) {
console.log("Exists!");
clearInterval(checkExist);
}
}, 100); // check every 100ms
But note - many times 3rd party code has an option to activate your code (by callback or event triggering) when it finishes to load. That may be where you can put your function. The interval solution is really a bad solution and should be used only if nothing else works.
Depending on which browser you need to support, there's the option of MutationObserver.
EDIT: All major browsers support MutationObserver now.
Something along the lines of this should do the trick:
// callback executed when canvas was found
function handleCanvas(canvas) { ... }
// set up the mutation observer
var observer = new MutationObserver(function (mutations, me) {
// `mutations` is an array of mutations that occurred
// `me` is the MutationObserver instance
var canvas = document.getElementById('my-canvas');
if (canvas) {
handleCanvas(canvas);
me.disconnect(); // stop observing
return;
}
});
// start observing
observer.observe(document, {
childList: true,
subtree: true
});
N.B. I haven't tested this code myself, but that's the general idea.
You can easily extend this to only search the part of the DOM that changed. For that, use the mutations argument, it's an array of MutationRecord objects.
This will only work with modern browsers but I find it easier to just use a then so please test first but:
ES5
function rafAsync() {
return new Promise(resolve => {
requestAnimationFrame(resolve); //faster than set time out
});
}
function checkElement(selector) {
if (document.querySelector(selector) === null) {
return rafAsync().then(() => checkElement(selector));
} else {
return Promise.resolve(true);
}
}
ES6
async function checkElement(selector) {
const querySelector = null;
while (querySelector === null) {
await rafAsync();
querySelector = document.querySelector(selector);
}
return querySelector;
}
Usage
checkElement('body') //use whichever selector you want
.then((element) => {
console.info(element);
//Do whatever you want now the element is there
});
A more modern approach to waiting for elements:
while(!document.querySelector(".my-selector")) {
await new Promise(r => setTimeout(r, 500));
}
// now the element is loaded
Note that this code would need to be wrapped in an async function.
Here's a minor improvement over Jamie Hutber's answer
const checkElement = async selector => {
while ( document.querySelector(selector) === null) {
await new Promise( resolve => requestAnimationFrame(resolve) )
}
return document.querySelector(selector);
};
To use:
checkElement('.myElement').then((selector) => {
console.log(selector);
});
If you want a generic solution using MutationObserver you can use this function
// MIT Licensed
// Author: jwilson8767
/**
* Waits for an element satisfying selector to exist, then resolves promise with the element.
* Useful for resolving race conditions.
*
* #param selector
* #returns {Promise}
*/
export function elementReady(selector) {
return new Promise((resolve, reject) => {
const el = document.querySelector(selector);
if (el) {resolve(el);}
new MutationObserver((mutationRecords, observer) => {
// Query for elements matching the specified selector
Array.from(document.querySelectorAll(selector)).forEach((element) => {
resolve(element);
//Once we have resolved we don't need the observer anymore.
observer.disconnect();
});
})
.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
Source: https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
Example how to use it
elementReady('#someWidget').then((someWidget)=>{someWidget.remove();});
Note: MutationObserver has a great browser support; https://caniuse.com/#feat=mutationobserver
Et voilà ! :)
Is better to relay in requestAnimationFrame than in a setTimeout. this is my solution in es6 modules and using Promises.
es6, modules and promises:
// onElementReady.js
const onElementReady = $element => (
new Promise((resolve) => {
const waitForElement = () => {
if ($element) {
resolve($element);
} else {
window.requestAnimationFrame(waitForElement);
}
};
waitForElement();
})
);
export default onElementReady;
// in your app
import onElementReady from './onElementReady';
const $someElement = document.querySelector('.some-className');
onElementReady($someElement)
.then(() => {
// your element is ready
}
plain js and promises:
var onElementReady = function($element) {
return new Promise((resolve) => {
var waitForElement = function() {
if ($element) {
resolve($element);
} else {
window.requestAnimationFrame(waitForElement);
}
};
waitForElement();
})
};
var $someElement = document.querySelector('.some-className');
onElementReady($someElement)
.then(() => {
// your element is ready
});
Here is a solution using observables.
waitForElementToAppear(elementId) {
return Observable.create(function(observer) {
var el_ref;
var f = () => {
el_ref = document.getElementById(elementId);
if (el_ref) {
observer.next(el_ref);
observer.complete();
return;
}
window.requestAnimationFrame(f);
};
f();
});
}
Now you can write
waitForElementToAppear(elementId).subscribe(el_ref => doSomethingWith(el_ref);
You can check if the dom already exists by setting a timeout until it is already rendered in the dom.
var panelMainWrapper = document.getElementById('panelMainWrapper');
setTimeout(function waitPanelMainWrapper() {
if (document.body.contains(panelMainWrapper)) {
$("#panelMainWrapper").html(data).fadeIn("fast");
} else {
setTimeout(waitPanelMainWrapper, 10);
}
}, 10);
Another variation of Iftah
var counter = 10;
var checkExist = setInterval(function() {
console.log(counter);
counter--
if ($('#the-canvas').length || counter === 0) {
console.log("by bye!");
clearInterval(checkExist);
}
}, 200);
Just in case the element is never shown, so we don't check infinitely.
A pure promise based JavaScript approach, you can tell for many milliseconds to wait.
const waitElementFor = function(query, ms = 3000) { // 3000 === 3 seconds
return new Promise((resolve) => {
var waited = 0;
var el = null;
var wi = setInterval(function() {
el = document.querySelector(query);
if (waited >= ms || el) {
clearInterval(wi);
if(el) {
resolve(el);
} else {
resolve(null);
}
}
waited += 10;
}, 10);
});
}
To use the function, simply use the following code in an asynchronous function.
var element = await waitElementFor('#elementID');
Snippet:
const waitElementFor = function(query, ms = 3000) { // 3000 === 3 seconds
return new Promise((resolve) => {
var waited = 0;
var el = null;
var wi = setInterval(function() {
el = document.querySelector(query);
if (waited >= ms || el) {
clearInterval(wi);
if(el) {
resolve(el);
} else {
resolve(null);
}
}
waited += 10;
}, 10);
});
}
async function snippetTestAyncFunction(){
var element = await waitElementFor('#elementID');
console.log(element);
}
snippetTestAyncFunction();
Maybe I'm a little bit late :), but here is a nice and brief solution by chrisjhoughton, which allows to perform a callback function when the wait is over.
https://gist.github.com/chrisjhoughton/7890303
var waitForEl = function(selector, callback) {
if (jQuery(selector).length) {
callback();
} else {
setTimeout(function() {
waitForEl(selector, callback);
}, 100);
}
};
waitForEl(selector, function() {
// work the magic
});
If you need to pass parameters to a callback function, you can use it this way:
waitForEl("#" + elDomId, () => callbackFunction(param1, param2));
But be careful! This solution by default can fall into a trap of an infinite loop.
Several improvements of the topicstarter's suggestion are also provided in The GitHub thread.
Enjoy!
This is for those of you who are running code in the Chrome console and not just hard-coded into the html.
user993683 above offered code that will work in your console code. His/her code is as follows:
while(!document.querySelector(".my-selector")) {
await new Promise(r => setTimeout(r, 500));
}
// now the element is loaded
He/she added that it "needs to be inside an async function." And if you are using code in Chrome's console then in fact you DON'T need to wrap it in a function. It will work just as written. You only need to place it in your code at the place right before you try to access the element to make sure it exists.
The only caveat is that it won't work on elements that are only sometimes present under other circumstances. Otherwise it will loop indefinitely if the element never downloads and you'll have to close the browser to stop the wait. Only use it for elements which you are certain will be present.
My company's form page has a dozen or more fields to fill out for each case number. And I have hundreds of case numbers in the script array every day. The elements do not all load simultaneously when changing the iFrame SRC and "onload" does not work in Chrome console scripts. So this method is a god-send to me and it saves me at least 45 minutes every day over the old generic async wait 10 seconds here or 30 seconds there due to fluctuating load times.
The only change I made is "getElementById" instead of the general "querySelector" because all of the elements I need have ID's.
while(!document.getElementById("myFrame").contentWindow.document.getElementById('someDocID')) {
await new Promise(r => setTimeout(r, 500));
}
// After completing the wait above it is now safe to access the element
document.getElementById("myFrame").contentWindow.document.getElementById('someDocID'
).innerText = "Smith, John R";
// and now click the submit button then change the SRC to a fresh form, and use
//*emphasized text* the code again to wait for it to fully load
I apologize to the monitors, but I added this as an answer because after several months of research on console scripts and waiting for elements to load, user993683's remark about a function finally made me realize that console scripts do not require a function for this code. My goal here is only to save other consoler script users the same learning curve that I went through.
Just use setTimeOut with recursion:
waitUntilElementIsPresent(callback: () => void): void {
if (!this.methodToCheckIfElementIsPresent()) {
setTimeout(() => this.waitUntilElementIsPresent(callback), 500);
return;
}
callback();
}
Usage:
this.waitUntilElementIsPresent(() => console.log('Element is present!'));
You can limit amount of attempts, so an error will be thrown when the element is not present after the limit:
waitUntilElementIsPresent(callback: () => void, attempt: number = 0): void {
const maxAttempts = 10;
if (!this.methodToCheckIfElementIsPresent()) {
attempt++;
setTimeout(() => this.waitUntilElementIsPresent(callback, attempt), 500);
return;
} else if (attempt >= maxAttempts) {
return;
}
callback();
}

Categories

Resources