jQuery: On load event not working consistently - javascript

I'm trying to lazy-load images using the following script (lazy-load.js):
function lazyLoadImage(imgContainers) {
var img = $('<img src="">');
imgContainers.each(function (i, elm) {
img.attr('src', $(elm).data("large"));
img.on('load', function () {
$(this).addClass('loaded');
});
img.addClass('picture');
$(elm).append(img.clone(true));
});
}
$(window).on('load',function () {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
});
The problem is, everything goes well if I load the script using <script></script> tag but when the script is loaded dynamically using jquery $.getscript() the script is not working consistently (i.e. sometimes the onload event is not triggering).
Loading script dynamically:
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
});
So, why the script is not working consistently??

window.load fires when the window finished loading. It doesn't fire a second time when you load more content via ajax because there is no way to tell for the browser when you will be finished loading additional content. So for all stuff you do via ajax you have to execute all functionality again.
In your case I guess you want these things to happen:
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
So I would say put this in a function and just call it when you finish loading the script:
function lazyloadimages() {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
}
$(window).on('load',function () {
lazyloadimages(); // notice this change, put the stuff in an extra function so you can reuse it!
});
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
lazyloadimages();
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
// oh no something went wrong, no need to lazyload something here!
});

Related

Run JS Function on Ajax Success & on Page Load

I have a function newCount that I run on Ajax success and it is working OK, however, I want to also run the same function every time the window is reloaded but for some reason I'm unable to call the function with newCount();
my code:
.ajax
$( document ).ajaxComplete(function() {
newCount();
});
.js
function newCount() {
var sum = 0;
$('.myclass').each(function() {
sum += parseFloat($(this).text());
});
// update count in html
$('#myid').html(sum);
}; // end count function
newCount(); // ajax not working when this in place
when I add newCount(); after the function, it will run correctly on page load, but the ajax will no longer work and vice versa.
What am I missing? How can I call the same function from the ajax success and every time the page is loaded?
Hey I've created this Plunker to show you how you should call the functions.
Here is the Javascript code.
<script>
(function(){
function newCount(msg) {
alert("message from: " + msg);
}; // end count function
debugger;
newCount("Page load");
$.get( "data.json", function( data ) {
alert( "Load was performed." );
});
$(document).ajaxComplete(function() {
newCount("ajax complete");
});
})();
EDIT 1
I've changed the Plunker so you can see that also works inside the $.ajax success property.
$.ajax({
url: "data.json",
data: "",
success: function() {
newCount("ajax complete");
}
});

ReferenceError after loading a script using $.getScript()

I have JS file hosted at https://cdn.rawgit.com/DarkPotatoKing/darkpotatoking.github.io/master/latest_version.js
When I run the following script on the browser console
jQuery.getScript("https://cdn.rawgit.com/DarkPotatoKing/darkpotatoking.github.io/master/latest_version.js")
.done(function() {
alert("done");
})
.fail(function() {
alert("fail");
});
I get a popup that says "done", but when I run
version.number()
the following error message is returned
ReferenceError: version is not define
Why is "version" not defined if the script is supposedly loaded properly?
Your script at has a syntax error, so it cannot be parsed. Correct your script, and version.number() will come:
var version = {
number: function() { return "1.1"; }; <==Syntax error here
}
Of course you must call version.number() from inside .done(function () {...})
EDIT
Ok i solved it for you, you need to change that uploaded file to this:
var version = {
number: function() { return "1.1"; }
}
you have a ; to much in that code.
And this is your new javscript/jquery code:
$.getScript( "https://cdn.rawgit.com/DarkPotatoKing/darkpotatoking.github.io/master/latest_version.js" )
.done(function( script, textStatus ) {
console.log(version.number);
})
.fail(function( jqxhr, settings, exception ) {
console.log("nope");
});
OLD
This is because your code is not in sync.
if you run version.number() inside the .done it must work.

Reloading DIV that contains just a script, and executing script

I cannot figure out how to reload the content within this div periodically:
<div id="redditFeed">
<script src="http://www.reddit.com/r/politics/hot/.embed?limit=10&t=all&style=off" type="text/javascript"></script>
</div>
I've tried some jquery, but the closest I've come is reloading the script into the div without executing it. Help would be much appreciated.
You can use $.getScript to load script again.
setTimeout(function() {
$.getScript( "http://www.reddit.com/r/politics/hot/.embed?limit=10&t=all&style=off", function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
}, 3000);

How can I fire a function in a click(function)?

I have a javascript file which I want to start when a div has been clicked.
I have already this when clicking the div "option_one", an input will be set to "Option 1":
$("#option_one").click(function() {
$("#input").val('Option 1');
});
How can I fire another js file after clicking the div?
I try something with getScript but I couldn't get it working.
Kind regards,
Arie
There is no need to load the calculate.js file on the click event. Just load it with the page load like so:
HTML:
<!--Your page HTML here... -->
<!--Before your closing body tag-->
<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript" src="calculate.js"></script>
JS:
// This is inside somefile.js
$("#option_one").click(function() {
$("#input").val('Option 1');
// This function is inside calculate.js
calculate();
});
$("#option_one").click(function() {
$("#input").val('Option 1');
$.getScript( "path/calculating.js" )
.done(function( script, textStatus ) {
//Just after the scripts finishes loading you will be able
//to perform/use functionality included on this script
console.log( textStatus );
})
.fail(function( jqxhr, settings, exception ) {
console.log("Triggered ajaxError handler.");
});
});

How to dynamically change my includes to js files?

I have a hidden div which contains my new links:
<div id="links" style="display:none">
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
...
</div>
The links I want to change are in my head:
<head id="myHead">
<!-- My olds links I want to replace -->
</head>
I've tried something like this:
updateLinks();
function updateLinks() {
var str = document.getElementById("links").innerHTML;
document.getElementById("myHead").innerHTML = str;
}
But my head don't receive the new links.
I want to update my links because I download html files and when I try to open them I have ERR_FILE_NOT_FOUND
Can you help me please?
What do you want is a asyncrounous module loader (AMD) like requirejs.
You can load all you files on demand. Using it it's simple to implement a lazy script loader. :)
Would simply loading the new js scripts suffice for your purposes?
You could use the jQuery method getScript to call it for each attribute src of your scripts in your div, like:
$("#links script").each(function() {
var src = $(this).attr("src");
$.getScript( src, function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
});
Here is your code
$(function() {
updateLinks();
});
function updateLinks() {
var po = document.querySelector('#links script');
var s = document.querySelector('head');
s.appendChild(po, s)
}
The jsFiddle: http://jsfiddle.net/BenoitNgo/6vca82wh/11/
The question has been answered already on this forum.

Categories

Resources