Reloading DIV that contains just a script, and executing script - javascript

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);

Related

jQuery: On load event not working consistently

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!
});

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.

What page is loaded in div

I'm using this command : $( "#result" ).load( "ajax/test.html" ); to load html page's content into div.
My question is how to know what I entered after I enterd it. A function that return the html page that is already inside the div.
You can store in a variable the currently loaded page (currentPage) and compare the page you load with the value of this variable:
<div id="result"></div>
<input type="button" onclick="load('test1.html')" value="Load">
<script>
var currentPage;
function load(page) {
if ( currentPage != page ) {
$("#result").load(page, function () {
currentPage = page;
});
}
else console.log('already loaded');
}
</script>
If you mean to access the contents of that page after it is loaded, You can use the callback of the function load.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
The callback is added as the second parameter one function and work within when it is charged.
You can also receive parameters in the callback.
Type: Function( String responseText, String textStatus, jqXHR jqXHR )
Full documentation have it here http://api.jquery.com/load/

how can i place two callback functions in a .load() function in jquery?

I'm having issues figuring out how to handle error on my page using .load() function, i already used the call back function for transitioning and i don't know how or to place the error code and make it work correctly....
i av this code.....
$('.menuLink:eq(0)').click(function(event) {
event.preventDefault();
setTimeout($('#navigation ul li').removeClass('expand', 'normal'), 1000);
$('section').hide().load('index.html section', function() {
$(this).fadeIn('slow');
});
});
I'll like to load any error that may occur in the section tag...
If you are using load() you can do the error checking in the same callback function. For example, as given in the JQuery documentation:
Display a notice if the Ajax request encounters an error.
<script>
$( "#success" ).load( "/not-here.php", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
In that callback function, first check for errors. Then, if there are no errors, do the fadeIn.
$('.menuLink:eq(0)').click(function(event) {
event.preventDefault();
setTimeout($('#navigation ul li').removeClass('expand', 'normal'), 1000);
$('section').hide().load('index.html section', function() {
// Check for errors here
$(this).fadeIn('slow');
});
});

Categories

Resources