I do update a html fragment via htmx.
How to load a JS library which is needed for this new snippet?
How to execute a function after the snippet got loaded?
Example:
I want to show an joyful animation (confetti) after the html snippet got added to the page.
This means the browser needs to load this:
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti#1.4.0/dist/confetti.browser.min.js"></script>
After loading above lib a JS function needs to get executed.
How to do this with htmx?
I found a solution. I guess it could get improved. Please leave a comment if you know a simpler way.
// lala.js
// this file gets loaded in the page (before the hx-post call)
function loadScript(url, callback) {
// https://stackoverflow.com/a/950146/633961
// Adding the script tag to the head as suggested before
var head = document.head;
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
};
document.body.addEventListener("confetti", function(evt){
var target = document.getElementsByClassName('htmx-settling')[0];
loadScript('https://cdn.jsdelivr.net/npm/canvas-confetti#1.4.0/dist/confetti.browser.min.js',
function () {
var myCanvas = document.createElement('canvas');
var rect = target.getBoundingClientRect();
myCanvas.setAttribute('style', 'position: absolute; top:' +
rect.top + 'px; left:' + rect.left + 'px');
target.appendChild(myCanvas);
var myConfetti = confetti.create(myCanvas, {
resize: true,
useWorker: true
});
myConfetti({
particleCount: 100,
spread: 160
// any other options from the global
// confetti function
})
})
})
On the server side I return the response like this (Django):
def confetti_hx(request):
...
response = HttpResponse(html)
response['HX-Trigger-After-Swap'] = 'confetti'
return response
Right now there is no way to load a new library on a page built in to htmx (this is a necessary feature IMO, please log an issue for it) so the confetti library should be included initially as part of your main site.
After you have included the external library in the main website, you can include a normal script tag that executes the confetti code necessary inline:
<script>
var myCanvas = document.createElement('canvas');
document.appendChild(myCanvas);
var myConfetti = confetti.create(myCanvas, {
resize: true,
useWorker: true
});
myConfetti({
particleCount: 100,
spread: 160
// any other options from the global
// confetti function
});
</script>
What I've been doing is use some Hyperscript to do something like this:
<script
src="https://cdn.jsdelivr.net/npm/canvas-confetti#1.4.0/dist/confetti.browser.min.js"
_="
on load
js
<enter code here>
end
end
"
></script>
Related
So basically I have a page with a few sections. Each sections contains 5-30 image icons that are fairly small in size but large enough that I want to manipulate the load order of them.
I'm using a library called collagePlus which allows me to give it a list of elements which it will collage into a nice image grid. The idea here is to start at the first section of images, load the images, display the grid, then move on to the next section of images all the way to the end. Once we reach the end I pass a callback which initializes a gallery library I am using called fancybox which simply makes all the images interactive when clicked(but does not modify the icons state/styles).
var fancyCollage = new function() { /* A mixed usage of fancybox.js and collagePlus.js */
var collageOpts = {
'targetHeight': 200,
'fadeSpeed': 2000,
'allowPartialLastRow': true
};
// This is just for the case that the browser window is resized
var resizeTimer = null;
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
// Here we apply the actual CollagePlus plugin
var collage = function(elems) {
if (!elems)
elems = $('.Collage');
elems.removeWhitespace().collagePlus(collageOpts);
};
var resetCollage = function(elems) {
// hide all the images until we resize them
$('.Collage .Image_Wrapper').css("opacity", 0);
// set a timer to re-apply the plugin
if (resizeTimer) clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
collage(elems);
}, 200);
};
var setFancyBox = function() {
$(".covers").fancybox({/*options*/});
};
this.init = function(opts) {
if (opts != null) {
if (opts.height) {
collageOpts.targetHeight = opts.height;
}
}
$(document).ready(function() {
// some recursive functional funk
// basically goes through each section then each image in each section and loads the image and recurses onto the next image or section
function loadImage(images, imgIndex, sections, sectIndex, callback) {
if (sectIndex == sections.length) {
return callback();
}
if (imgIndex == images.length) {
var c = sections.eq(sectIndex);
collage(c);
images = sections.eq(sectIndex + 1).find("img.preload");
return loadImage(images, 0, sections, sectIndex + 1, callback);
}
var src = images.eq(imgIndex).data("src");
var img = new Image();
img.onload = img.onerror = function() {
images[imgIndex].src = src; // once the image is loaded set the UI element's source
loadImage(images, imgIndex + 1, sections, sectIndex, callback)
};
img.src = src; // load the image in the background
}
var firstImgList = $(".Collage").eq(0).find("img.preload");
loadImage(firstImgList, 0, $(".Collage"), 0, setFancyBox);
});
}
}
From my galleries I then call the init function.
It seems like my recursive chain being triggered by img.onload or img.onerror is not working properly if the images take a while to load(on slow networks or mobile). I'm not sure what I'm missing here so if anyone can chip in that would be great!
If it isn't clear what is going wrong from the code I posted you can see a live example here: https://www.yuvalboss.com/albums/olympic-traverse-august-2017
It works quite well on my desktop, but on my Nexus 5x it does not work and seems like the finally few collage calls are not happening. I've spent too long on this now so opening this up to see if I can get some help. Thanks everyone!
Whooooo I figured it out!
Was getting this issue which I'm still unsure about what it means
[Violation] Forced reflow while executing JavaScript took 43ms
Moved this into the callback that happens only once all images are loaded
$(window).bind('resize', function() {
resetCollage(); // resize all collages
});
For some reason it was getting called early even if the browser never resized causing collage to get called when no elements existed yet.
If anyone has any informative input as to why I was getting this js violation would be great to know so I can make a better fix but for now this works :):):)
I am lazy loading my Facebook comments plugin, but the plugin takes a while to load. I want the user to know that it's loading by adding a loading GIF. I know how to add the loading GIF, but I don't know how to remove it once the comments plugin has loaded fully. This is what I've tried:
<img id="loading" src="/media/assets/loading.gif">
<script>
function loadAPI() {
var js = document.createElement('script');
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5";
document.body.appendChild(js);
js.onload=loading();
}
window.onscroll = function () {
var rect = document.getElementById('comments').getBoundingClientRect();
if (rect.top < window.innerHeight) {
loadAPI();
window.onscroll = null;
}
}
//Function used to remove GIF
function loading(){
var loading = document.getElementById('loading');
loading .parentNode.removeChild(loading);
}
</script>
<div id="fb-root"></div>
<div id="comments" class="fb-comments" data-href="http://example.com" data-numposts="5" data-colorscheme="light"></div>
The code I am using, displays the GIF when the user scrolls to the comments section part, and then removes it after all the functions have been invoked. This is not what I want. I want it to get removed after the Faceboook Comments plugin has been displayed. My code removes the GIF a good bit of time prior the plugin displaying. What can I do to fix this issue?
First of all, you are invoking the loading function when you'd actually need to pass the reference to js.onload, so the loading callback gets executed before the Facebook plugin has even finished loading the javascript.
So, change
js.onload=loading();
to
js.onload=loading;
Now the gif gets removed when the plugin itself has finished loading, but we can do better than that. The plugin will set a global object FB which you can use to subscribe to the render event of the comments (source), like so:
FB.Event.subscribe("xfbml.render", function(){
//The comments are now rendered, remove the image
});
Putting it all together:
<img id="loading" src="/media/assets/loading.gif">
<script>
function loadAPI() {
var js = document.createElement('script');
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5";
document.body.appendChild(js);
js.onload=loading;
}
window.onscroll = function () {
var rect = document.getElementById('comments').getBoundingClientRect();
if (rect.top < window.innerHeight) {
loadAPI();
window.onscroll = null;
}
}
//Function used to remove GIF
function loading(){
FB.Event.subscribe('xfbml.render', function(){
var loading = document.getElementById('loading');
loading.parentNode.removeChild(loading);
});
}
</script>
<div id="fb-root"></div>
I want to add an image by Javascript, then calculating the html element width as
window.onload=function(){
document.getElementById('x').addEventListener('click', function(e){
var el = document.getElementById('xx');
el.innerHTML = '<img src="img.jpg" />';
var width = el.offsetWidth;
.....
}, false);
}
but since JavaScript conduct all processes simultaneously, I will get the width of the element before loading the image. How can I make sure that the image has been loaded into the content; then calculating the element width?
UPDATE: Thanks for the answers, but I think there is a misunderstanding. img src="img.jpg" /> does not exist in the DOM document. It will be added later by Javascript. Then, when trying to catch the element by Id, it is not there probably.
You can give the img an ID and do the following :-
var heavyImage = document.getElementById("my-img");//assuming your img ID is my-img
heavyImage.onload = function(){
//your code after image is fully loaded
}
window.onload=function(){
document.getElementById('x').addEventListener('click', function(e){
var el = document.getElementById('xx');
var img = new Image();//dynamically create image
img.src = "img.jpg";//set the src
img.alt = "alt";
el.appendChild(img);//append the image to the el
img.onload = function(){
var width = el.offsetWidth;
}
}, false);
}
This is untested, but if you add the image to the DOM, set an onload/load event-handler and then assign the src of the image, the event-handling should fire (once it's loaded) and allow you to find the width.
This is imperfect, though, since if the image is loaded from the browser's cache the onload/load event may not fire at all (particularly in Chromium/Chrome, I believe, though this is from memory of a bug that may, or may not, have since been fixed).
For the chrome bug you can use the following:-
var BLANK = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';//create a blank source
var tImg = document.getElementById("my-img");//get the image
var origSrc = tImg.src;//get the original src
tImg.src = BLANK;//change the img src to blank.
tImg.src = origSrc;//Change it back to original src. This will lead the chrome to load the image again.
tImg.onload= function(){
//your code after the image load
}
You can use a library called PreloadJS or you can try something like this:
//Somewhere in your document loading:
loadImage(yourImage, callbackOnComplete);
function loadImage(image, callbackOnComplete){
var self = this;
if(!image.complete)
window.content.setTimeout(
function() { self.loadImage(image, callbackOnComplete)}
,1000);
else callbackOnComplete();
}
I did this when I worked with images base64 which delay on loading.
I have a problem about jQuery and javascript code; when I write this jQuery below between </head> and <body>
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j('#page_effect').fadeIn(3000);
});
</script>
and then write javascript code in body tag
<script src="bubbles.js"></script>
<script type="text/javascript">
bubblesMain(new Object({
type : 'linear',
minSpeed : 100,
maxSpeed : 400,
minSize : 30,
maxSize : 55,
num : 100,
colors : new Array('#FF0000','#FFFFFF','#FFCC99', '#FF33CC')
}));
</script>
then jQuery code can work , but javascript code doesn't work. Finally I found that when I resize the browser after the first loading, it's OK to run.
the bubble.js is to automatically create a canvas element and then raises some bubbles with animation inside canvas.
the partly code is on below :
function bubblesMain(obj){
bubbleResize();
bubbles = new bubbleObject(obj);
bubbles.createBubbles();
setInterval(start,1000/60);
};
//WHEN WINDOW HEIGHT IS CHANGED, REMAKE THE CANVAS ELEMENT
window.onresize = function(event) {
bubbleResize();
}
function bubbleResize(){
var height = parseInt(document.getElementById("canvasBubbles").clientHeight);
var width = parseInt(document.getElementById("canvasBubbles").clientWidth);
document.getElementById("canvasBubbles").innerHTML = '<canvas id="canvas" width="'+width+'px" height="'+height+'px"></canvas>';
}
function start(){
var canvas = document.getElementById("canvas");
canvas.width = canvas.width;
bubbles.move();
bubbles.draw();
};
and I have a <div id="canvasBubbles"></div> indise html.
Then after I added the following code into bubbles.js, It's work to run.
window.onload = function(event) {
bubbleResize();
}
I wonder if someone can suggest a smarter solution to this? thank you.
As stated in the other answers, the <script> tags should be the last thing before the </body> tag. See this question.
The problem with where you've put the tags is that the body of the HTML page hasn't loaded and is therefore not available for manipulation. The reason the window.onload and window.onresize work is because they are called later, when the body of the document is available for manipulation with JS.
Given the details provided in your question, you don't need the jQuery.noConflict() statement.
Here is an alternate version of your code that should do the same thing but with a bit more efficiency. Put it at the end of the body element, just before the </body> tag. I haven't tested it since I don't have all the scripts needed (bubbles, etc).
<!-- this goes at the end of your body element, just before the closing tag -->
<script type="text/javascript" src="bubbles.js"></script>
<script type="text/javascript">
$.ready(function(){
var canvasWrap,
canvasElm,
bubbles;
init();
setInterval(update, 1000/60);
window.onresize = resize;
$('#page_effect').fadeIn(3000);
function init(){
canvasWrap = document.getElementById("canvasBubbles");
canvasElm = document.createElement('canvas');
canvasElm.setAttribute('id', 'canvas');
canvasElm.setAttribute('width', canvasWrap.clientWidth);
canvasElm.setAttribute('height', canvasWrap.clientHeight);
canvasWrap.appendChild(canvasElm);
bubbles = new bubbleObject({
type: 'linear',
minSpeed: 100,
maxSpeed: 400,
minSize: 30,
maxSize: 55,
num: 100,
colors: ['#FF0000','#FFFFFF','#FFCC99', '#FF33CC']
});
bubbles.createBubbles();
update(); // you might not need this
}
function resize() {
canvasElm.setAttribute('width', canvasWrap.clientWidth);
canvasElm.setAttribute('height', canvasWrap.clientHeight);
}
function update(){
// canvasElm.width = canvasElm.width; // is this a hack for something?
bubbles.move();
bubbles.draw();
};
});
</script>
You can write all this inside <body>...</body> or inside <head> ... </head>
NOT works between </body> and <head> tag (maybe works for some less formal browser like old IE).
Script tags should always go at the bottom of the page directly before the tag unless the codes needs to be executed before then for some reason.
And as far as I know, the jQuery noConflict() method is only required when you are using two different libraries that both use the dollar sign, aka jQuery and MooTools, on the same page. You can use jQuery and vanilla javascript without having to use noConflict without any problems.
It's easy to keep javascript waiting for some images to load if those are classic HTML images.
But I can't figure how to do the same if the image is loaded as a CSS backuground-image!
Is it possible?
The jQuery .load() method doesn't seem to apply.. and I'm short of ideas
It looks for elements with src attribute or backgroundImage css property and calls an action function when theirs images loaded.
/**
* Load and wait for loading images.
*/
function loadImages(images, action){
var loaded_images = 0;
var bad_tags = 0;
$(images).each(function() {
//alert($(this).get(0).tagName+" "+$(this).attr("id")+" "+$(this).css("display"));
var image = new Image();
var src = $(this).attr("src");
var backgroundImage = $(this).css("backgroundImage");
// Search for css background style
if(src == undefined && backgroundImage != "none"){
var pattern = /url\("{0,1}([^"]*)"{0,1}\)/;
src = pattern.exec(backgroundImage)[1];
}else{
bad_tags++;
}
// Load images
$(image).load(function() {
loaded_images++;
if(loaded_images == ($(images).length - bad_tags))
action();
})
.attr("src", src);
});
}
One alternate approach would be to fetch the image data via AJAX as a base64 encoded png and apply it to the element's background-image property.
For example:
$.get('/getmyimage', function(data) {
// data contains base64 encoded image
// for ex: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
$('#yourElement').css('background-image', 'url("' + data + '")');
});
You will also need a server side script that reads the image, converts it into base64 encoded png (and cache it maybe) and return the same.
Try this one...
Its a jQuery-Plugin which gives you control to wait for images to be loaded
Project-Home
Thread # SO
Official way to ask jQuery wait for all images to load before executing something
Answer # SO
(ShortLink)
this is untested code but try this:
$(document).ready(
function()
{
var imgSrc = $('theTargerElement').css('background-image');
var imgTag = $('<img>').attr('src',imgSrc).appendTo( 'body' );
}
);
$(document)
.load(
function()
{
// do stuff
}
);