Am currently using head.js to defer loading of js files for my website. Am using colorbox in my project. The problem is that at times, the colorbox doesnt fully load (it opens the colorbox in a new page rather than in a dialog), but when i do several refreshes, it finally loads.
I guess it might be that the page content that is meant to open the colorbox dialog gets loaded even before colorbox js files are fully loaded by head.js. Is this the actual cause?
I would want to have colorbox display correctly each time without need for a refresh.
How do I keep the colorbox page code to execute only after head.js finishes loading all its dependent files?
thanks. nikk
Put your colorbox html code in a div.
<div id="colorBoxDiv" style="display:none;">
</div>
In the last line of head.js, add this code:
$("#colorBoxDiv").html($("#colorBoxDiv").html()).show();
head.js had a lot of different options how to do that. you can run callback function when needed files loaded, or use test feature api call.
For example:
// queue scripts and fire a callback when loading is finished
head.load("file1.js", "file2.js", function() {
// do something
});
// same as above, but pass files in as an Array
head.load(["file1.js", "file2.js"], function() {
// do something
});
// you can also give scripts a name (label)
head.load({ label1: "file1.js" }, { label2: "file2.js" }, function() {
// do something
});
// same as above, but pass files in as an Array
head.load([{ label1: "file1.js" }, { label2: "file2.js" }], function() {
// do something
});
// Labels are usually used in conjuntion with: head.ready()
head.ready("label1", function() {
// do something
});
// Actually if no label is supplied, internally the filename is used for the label
head.ready("file1.js", function() {
// do something
});
More in documentation
Related
Issue
I have a loading screen used to fill time while a <div> is idling and I want it to disappear after the total blocking time (TBT) is done. I am new to front-end development and not 100% on how to do this.
Failed solutions
My loading screen is required when the user clicks on the builder section. Both the loading screen and builder sections are loaded with the document and are hidden using .hide() and then shown using .fadeIn().
I have tried using the .load() and .on("load", function(){}) jQuery methods like so:
// 'build' is a var declared as $('.build-container');
$(build).ready(function() {
console.log("Build is loaded");
hideLoadingScreen();
});
But the issue with this is that build is loaded with the document, not when the user clicks the build button on the navbar and after some research, I found that it isn't possible to lazy load an element if it is in the HTML file.
Below is a screenshot of the TBT time, is there a jQuery way to .hide() after the this is completed?
I think you can change with the following
$(build).ready(function() {
console.log("Build is loaded");
hideLoadingScreen();
})
// NEW
build.ready(function() {
console.log("Build is loaded");
hideLoadingScreen();
})
Because build is already defined as a JQuery result variable (// 'build' is a var declared as $('.build-container');). I let you try it :)
With jQuery 3.3.1 load() I am adding content with a few HTML img tags inside and then I want to check the viewport for visible elements AFTER
all the pictures have finished loading.
My problem is that I am unable to know when the dynamically added pictures have been fully loaded in my <div id="#content">.
This is my JS code for loading the new content:
// Replace the #content with content from a file containing a few `img` tags
$("#content").load("image-list.html", function() {
console.log("Now my images have fully loaded???");
});
I have tried this:
// Show me which event is triggered after load()
$(window).on("load resize scroll", function(event) {
console.log(event);
});
// Check if I can get when the images have fully loaded
$("img").on("load", function() {
console.log("Load image event???");
});
I also have tried some black-magic with waiting X milliseconds and looping through all image tags but this is for sure NOT the way to go as it is obscure!
The result of the above is:
I get the Now my images have fully loaded message immediately after I have loaded the file but it does not wait to show the message to after everything has been rendered
I do not get the console.log(event) message at all
I do not get any Load image event messages at all
I am debugging this by slowing down the speed with Chromes network option:
The reason your Load image event??? log is not firing, because you are not late binding the event handler on the images, thus, the on function will not fire for images that were added dynamically to your html.
To late bind, you can modify that function the following way:
$(document).on('load', 'img', function() {
console.log("Load image event???");
});
But if an image takes a long time to load, and you are trying to do something after all the new images were loaded which came from your image-list.html, I suggest something like the below approach:
Try putting the load listener, inside the callback function of the load method, like this:
$("#content").load("image-list.html", function() {
var numberOfImages = jQuery("#content img").length;
$("#content img").one('load', function() {
numberOfImages--;
if (numberOfImages == 0) {
console.log("All the images have loaded");
}
});
$("#content img").each(function() {
if (jQuery(this)[0].complete) jQuery(this).trigger("load");
});
});
You just have to be careful, as apparently, the load event will not fire, if the image you are loading was already cached, and loaded from the cache. There are workarounds for that too.
EDIT: The above code will take care for the situation where the images are loaded from cache also.
I have an API which works appending the fancybox script to the head tag of the client's web page, but obviously this happens after the dom is ready, so the init function of fancybox is not called
In fancybox.js:
$(document).ready(function() {
$.fancybox.init();
});
I've tried changing it to :
$(document).bind('ready', function() {
$.fancybox.init();
});
and then triggering the dom ready function in different ways (one by one):
$(document).trigger("ready");
$().trigger("ready")
$().ready();
I've also tried calling the init function when the script is loaded:
$.fancybox.init();
Nothing seems to work.
I'm sure that the fancybox.css, the fancybox.js and even mousewheel.js and easing.js are loaded in the documment before trying all that, I also added a timeout to be sure.
So the question is, how can the fancybox plugin be initialized after appending the js to the head tag?
I don't think you need to call $.fancybox.init(); but just initialize the proper selector after the fancybox script has been loaded so I would try within the API something like :
if (!jQuery.fn.fancybox){
// fancybox is not loaded
jQuery.getScript("{path}/jquery.fancybox.js"); // you may need to change the path
setTimeout(function(){
// init fancybox selector
jQuery(".selector").fancybox();
}, 100); // delay selector initialization
} else {
// fancybox script is ready so initialize (re-init) selector
jQuery(".selector").fancybox();
};
So I basically have a load that loads the file to an id and when that load is done I want to load another file to an id which is inside the first load.
Does it sound a bit weird?
We can add a bit of code to describe it easier.
function interestsList() {
$('.interests_editlist').fadeIn(500).load('/snippets/interests_edit.php');
}
That is how it looks right now. I want to add this line
$('#interests_list').load('/snippets/interests_list.php');
but if I just add it, it doesn't load. The reason might be that it tries to load before the load above is done. That is a problem because #interests_list is loaded with the first load.
How do I make the second load to start loading when the first one is finished?
load() method accept a complete callback:
function interestsList() {
$('.interests_editlist').fadeIn(500)
.load('/snippets/interests_edit.php', function () {
$('#interests_list').load('/snippets/interests_list.php');
});
}
you can use .load() callback to know when load is complete
try this:
function interestsList() {
$('.interests_editlist').fadeIn(500).load('/snippets/interests_edit.php', function() {
//callback function when the first load is complete
$('#interests_list').load('/snippets/interests_list.php');
});
}
I'm using the jQuery Loader plugin to load files on demand- tagit plugin.
The issue is that if I add an alert to the callback function fired on load the plugin loaded seems to work, if I remove the alert, the plugin fails.
Any ideas why is this happening?
$(document).ready(function(){
$("#mytags").Loader(
{
url: [
'media/plugins/tagit/css/jquery-ui/jquery.ui.autocomplete.custom.css',
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js',
'media/plugins/tagit/js/jquery-ui/jquery-ui-1.8.autocomplete.min.js',
'media/plugins/tagit/js/tag-it.js'
],
success: function(target) {
//alert('loaded');
$(target).tagit({
availableTags: ["tag1","tag2", "tag3"],
values: ["tag2"]
});
}
}
});
Im testing this on my local XAMP environment.
The possible reason why blocking code execution with alert() helps is that, while JavaScript execution stops (including intervals and timeouts), external resources (JS, CSS, images, and xmlhttprequests) may finish loading. But, again, until the code following the alert() completes, none of these external scripts will run and no DOM events will fire.
An example when alert() makes a difference: http://jsfiddle.net/p9Nff/
It's problaly related with async, do you try to force async to false?
When the alert open the script have time to load your plugins. or it's what Alexey said, your DOM is not ready, put your code into $(function(){ /code here/ });