Simple function to run javascript after specific content is loaded.
jQuery dependant.
Useful for dealing with resizing iframes after content is loaded to avoid scroll bars in the iframe. Also serves as an alternative to waitForKeyElement when tinkering with userscripts et.
Doc:
/*
Usage:
waitForAsyncElement(selector, code, delay, timeout, fallback);
Breakdown:
selector: jQuery selector as string: "#yourElementHere"
code: function with code to run: function(){"code here"};
delay: delay in ms after element is loaded: default 30ms
timeout: stop execution if element is not loading: default 5000ms
fallback: if timed out run fallback, example: function(){alert("async did not load")")}
Example:
*/
waitForAsyncElement("#some-data", function(){
console.log($("#some-data").val());
})
//Example with fallback:
waitForAsyncElement("#some-data", function(){
console.log($("#some-data").val());
}, 30, 5000, function(){
console.log("#some-data did not load");
})
/*
Example for dealing with resizing iFrame after its loaded:
Note the extra 300ms delay to wait for iframe content to load,
iFrame.onload could have been used instead, but seem to fail on mobile.
*/
onElementLoaded("#iFrame1", function(){
var iFrame = document.getElementById('iFrame1');
iFrame.height = iFrame.contentWindow.document.body.scrollHeight + 100;
}, 300);
Code language: JavaScript (javascript)
Code:
var waitForAsyncElement = function(elementSelector,
callback,
delay = 30,
timeoutms = 5000,
timeoutFallback = function(){return}){
var intervl = setInterval(function(){
if (jQuery(elementSelector).length){
clearInterval(intervl);
setTimeout(() => {callback()}, delay);
}
}, 300);
if (timeoutms !== 0){
setTimeout(() => {
clearInterval(intervl);
timeoutFallback();
}, timeoutms);
}
};
Code language: JavaScript (javascript)
Licence:
Public Domain or MIT, whichever suits you best. However please keep me in the loop if you build on the function, make and improvements and such 🙂