Here is my problem:
I have threes iframes, with some kind of content. I need to "start" them with for example 1 sec interval. But! I can't change content of html file at all (i have content watcher that refreshes page after any change of file)
Is there any possibility to delay serving contents of iframes?
Of course something like that: jQuery .ready in a dynamically inserted iframe or that: Load iFrame after page load or anything i could find here doesnt work.
Don't give them an src and use a data attribute instead
<iframe data-src="http://google.com"></iframe>
Then loop over them and set the src based on whatever interval you want
var frameInterval = 1000;
$('iframe').each(function(index){
var $frame = $(this), src = $frame.data('src');
setTimeout(function(){
$frame.attr('src', src);
}, index * frameInterval );
});
The comments in question about content watcher are not clear enough to understand what that issue means with regard to this situation
Related
Sometimes when this script executes on a page, especially if it is the first time the browser loads the page, the contents of the iframe will show the page at test.html but it will be an older page that is missing some changes that the actual test.html when loaded manually from the directory does contain. Every time setInterval() runs, the contents of the iframe will still be outdated.
If the whole page is refreshed, say by clicking the refresh button, the contents of the iframe will be updated and setInterval() will cause the iframe to show the current test.html. However, it seems like given enough time setInterval() will sometimes stop loading the current contents of test.html.
I suspect the answer may have something to do with Why is it suggested to avoid .innerHTML? or Whats wrong here, why is innerHTML not working? but I am an extreme novice and do not fully understand the limitations of innerHTML.
<script>
// Loads into a div an iframe that itself loads a page from the server.
document.getElementById("divy").innerHTML="<iframe width='600' height='800' id='cat' src='test.html'></iframe>";
iframe = document.getElementById('cat');
//Scrolls iframe to bottom.
iframe.onload = function () {
iframe.contentWindow.scrollTo(0,iframe.contentWindow.document.body.scrollHeight);
console.log(iframe.contentWindow.document.body.scrollHeight);
}
refresh_rate = 3000
// Every refresh_rate miliseconds, replaces the html inside the div with a new iframe so any changes to the page test.html are now shown.
setInterval(function(){
var element = document.getElementById('cat');
element.parentNode.removeChild(element);
document.getElementById("divy").innerHTML="<iframe width='600' height='800' id='cat' src='test.html'></iframe>";
iframe = document.getElementById('cat');
var x = document.getElementsByTagName('*');
console.log(x)
iframe.onload = function () {
iframe.contentWindow.scrollTo(0,iframe.contentWindow.document.body.scrollHeight);
console.log(iframe.contentWindow.document.body.scrollHeight);
}
}, refresh_rate);
</script>
Your test page is being cached somewhere, you need to bust the cache each time the page reloads. I've added a basic cache buster to a tidied up version of your code.
However, it would be much simpler to just update the src attribute of the iframe, rather than pull out the whole element and reinsert it every three seconds.
<script>
function loadCat(cacheBuster){
document.getElementById("divy").innerHTML="<iframe width='600' height='800' id='cat' src='test.html?'+cacheBuster></iframe>";
var iframe = document.getElementById('cat');
//Scrolls iframe to bottom.
iframe.onload = function () {
iframe.contentWindow.scrollTo(0,iframe.contentWindow.document.body.scrollHeight);
console.log('iFrame height: ', iframe.contentWindow.document.body.scrollHeight);
}
}
function removeCat(){
var element = document.getElementById('cat');
element.parentNode.removeChild(element);
}
var refresh_rate = 3000;
var counter = 0;
loadCat(counter);
// Every refresh_rate miliseconds, replaces the html inside the div with a new iframe so any changes to the page test.html are now shown.
setInterval(function(){
removeCat()
loadCat(++counter);
}, refresh_rate);
</script>
I inherited a project where a page is loaded, then code attached to that page fills in a div with dynamically generated html - it basically fills an existing div with a html string.
This string contains links to images, etc.
I want to tell when all the images, etc have loaded- I cannot seem to get any jQuery standard checks
to work - ie I have tried attaching $(window).load() after the dynamic stuff has been inserted.
I am wondering if I should write $(window).load() dynamically as well, or if there is any other
method- ie $("#thediv").load (doesn't seem to work. I cannot query all the new html for image tags, etc-
too much stuff is being put in.
The $(window).load() doesn't work for dynamic content as far as I know. You can use the .load event for each image separated. Here's an example:
var container = $("<div> ... Stuff ... </div>");
var images = container.find('img');
var imageIdx = 0;
images.load(function(){
imageIdx++;
if (imageIdx == images.length){
callback();
}
});
Where callback() is the function that runs after all images where loaded.
From my comment: window load applies to the initial page load only. Not dynamic loading of content within it. Attach load handlers to each loaded image element and count them.
This is the shortest version I could come up with for you:
// After HTML load finishes
var img = 0;
var imgCount = $("#thediv img").load(function(){
if (++img == imgCount){
// We are done loading all images!
}
}).length;
$(window).ready() only applies to the content within the HTML file and you can only use load to attach an onload event handler to a specific image (not a container), something like this might work for you.
window.ImageLoadHandled = false;
window.ImageLoadCount = 0;
function ImageLoadHandler() {
// guard against calling this function twice
if(window.ImageLoadHandled) return;
window.ImageLoadHandled = true;
// All images have loaded || timeout expired...
}
$("#myAjaxedDiv img").load( function() {
window.ImageLoadCount++;
if( window.ImageLoadCount == $("#myAjaxedDiv img").length ) {
// all images in #myAjaxedDiv have loaded
ImageLoadHandler();
}
});
// if images haven't loaded after 5 seconds, call the code
setTimeout( ImageLoadHandler, 5000 )
The only problem with this is that if an image fails to load for whatever reason, the code will never be hit, which is quite risky. To counteract this I'd recommend creating a setTimeout() method to call your code after a few seconds timeout in-case there is a problem loading images (client or server side) and I've also taken #TrueBlueAussie's correction into account in the edit.
Your alternative is to preload the images with your HTML page
I have following div inside my jsp file
<div id="myDiv">
<img alt="" src="http://localhost:8080/chartDemo/servlet/ChartDemoServlet">
</div>
I want to automatically refresh the image at some interval.
I have tried with <meta http-equiv="Refresh"> it works perfect but refreshes the whole page.
How do I refresh only the image?
I want to automatically refresh that div at some interval.
With what content? Or does the img change every time?
If so:
setInterval(function() {
$("#myDiv").html('<img alt="" src="http://localhost:8080/chartDemo/servlet/ChartDemoServlet">');
}, 1000);
...should do it, once a second (1000ms = 1 second), provided the cache headers on the data returned by the img's src URL are correct (otherwise, the browser may cache the earlier version). What that does is completely tear down the contents of the div, and then assign the given markup to it, which should recreate the img element and cause a re-fetch (again, provided the headers are right).
setInterval(function() {
// use to prevent browser cache
var d = new Date();
$("#myDiv img").attr("src", "http://localhost:8080/chartDemo/servlet/ChartDemoServlet?"+d.getTime());
}, 3000); // every 3 seconds.
<div id="myDiv" onload="JavaScript:timedRefresh(5000);">
<img alt=""
src="http://localhost:8080/chartDemo/servlet/ChartDemoServlet">
</div>
put it in javascript
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
You need to use window.setInterval timer. In that function you give change the img src.
soemthing like this
//timer function
window.setInterval(refreshImage,1000);
function refreshImage()
{
$('#urdiveid img').attr('src')='new location';
}
It can be done with JavaScript Timeout Function
var t=setTimeout("functiontoCall()", 3000)
You can write your own in FunctiontoCall() to load content in myDiv. It can be ajax call or simple Dom Manipulation
I have an html file that I want to be loaded from various pages into a dijit.contentpane. The content loads fine (I just set the href of the contentpane), but the problem is that javascript within the html file specified by href doesn't seem to be executed at a consistent time.
The final goal of this is to load an html file into a contentpane at an anchor point in the file (i.e. if you typed in index.html#tag in order to jump to a certain part of the file). I've tried a few different methods and can't seem to get anything to work.
What I've tried:
1.
(refering to the href of the dijit.contentpane)
href="page.htm#anchor"
2.
(again, refering to the href of the dijit.contentpane -- didn't really expect this to work, but decided to try anyways)
href="#anchor"
3. (with this last try inside the html specified by href)
<script type="text/javascript">
setTimeout("go_to_anchor();", 2000);
function go_to_anchor()
{
location.href = "#anchor";
}
</script>
This last try was the closest to working of all of them. After 2 seconds (I put the delay there to see if something in the dijit code was possibly loading at the same time as my javascript), I could see the browser briefly jump to the correct place in the html page, but then immediately go back to the top of the page.
Dojo uses hashes in the URL to allow bookmarking of pages loaded through ajax calls.
This is done through the dojo.hash api.
So... I think the best thing you can do is use it to trigger a callback that you write inside your main page.
For scrolling to a given position in your loaded contents, you can then use node.scrollIntoView().
For example, say you have a page with a ContentPane named "mainPane" in which you load an html fragment called "fragment.html", and your fragment contains 2 anchors like this :
-fragment.html :
Anchor 1
<p>some very long contents...</p>
Anchor 2
<p>some very long contents...</p>
Now say you have 2 buttons in the main page (named btn1 and btn2), which will be used to load your fragment and navigate to the proper anchor. You can then wire that up with the following javascript, in your main page :
<script type="text/javascript">
require(['dojo/on',
'dojo/hash',
'dojo/_base/connect',
'dijit/layout/BorderContainer',
'dijit/layout/ContentPane',
'dijit/form/Button'],
function(on, hash, connect){
dojo.ready(function(){
var contentPane = dijit.byId('mainPane');
var btn1 = dijit.byId('btn1');
var btn2 = dijit.byId('btn2');
btn1.on("Click", function(e){
if (!(contentPane.get('href') == 'fragment.html')) {
contentPane.set("href", "fragment.html");
}
hash("anchor1");
});
btn2.on("Click", function(e){
if (!(contentPane.get('href') == 'fragment.html')) {
contentPane.set("href", "fragment.html");
}
hash("anchor2");
});
// In case we have a hash in the URL on the first page load, load the fragment so we can navigate to the anchor.
hash() && contentPane.set("href", "fragment.html");
// This callback is what will perform the actual scroll to the anchor
var callback = function(){
var anchor = Array.pop(dojo.query('a[href="#' + hash() + '"]'));
anchor && anchor.scrollIntoView();
};
contentPane.on("DownloadEnd", function(e){
console.debug("fragment loaded");
// Call the callback the first time the fragment loads then subscribe to hashchange topic
callback();
connect.subscribe("/dojo/hashchange", null, callback);
});
}); // dojo.ready
}); // require
</script>
If the content you're loading contains javascript you should use dojox.layout.ContentPane.
I have run into numerous sites that use a delay in loading images one after the other and am wondering how to do the same.
So i have a portfolio page with a number of images 3 rows of 4, what i want to happen is for the page to load,except for the images in img tags. Once the page has loaded i want images 1 of each row to load then say 0.5 seconds later the next image in the row(s) and so no. I'm going to have a loading gif in each image box prior to the actual image being displayed.
I know its doable but cant seem to find the term for doing this. This is purely for looks as it is a design site.
Thanks for the help.
This is very easy to do in jQuery
$('img').each(function(i) {
$(this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/Svs7p/3
For fading in rows one after the other in a table it just means changing the selector slightly. Remember to change from div to img -- I just used div for testing
$('tr').each(function(i) {
$('td div', this).delay((i + 1) * 500).fadeIn();
});
Fiddle: http://jsfiddle.net/garreh/2Fg8S/
Here is what you can do, you can load the image tags with out the src and using a custom property:
<img alt='The image' path='image/path.jpg' />
then you can use javascript to load the images when the site is loaded or whenever you please;
// simplified
window.onload = function () {
var images = document.getElementsByTagName('img');
// loop and assign the correct
for (var i =0; i < images.length;i++){
var path = images[i].getAttribute('path');
images[i].src = path;
}
}
I hope you get the concept of how the images are delayed
**please note the path attribute is not a standard one.
The easiest way I can think to do this is to have a table set up that will eventually hold the image tags, but have none on load. Javascript can loop through an array of image urls, and insert those image tags into random locations on the table.
If you want to have the delay, setInterval is the perfect tool. http://www.w3schools.com/jsref/met_win_setinterval.asp
// You can hard-code your image url's here, or better still, write
// a server-side script that will read a directory and return them
// so it is fully dynamic and you can add images without changing code
unpickedImages = array();
// Start loading
loadAllImages = setInterval( insertImage, 600 );
function insertImage() {
if( unpickedImages.length > 0 ) {
var imageUrl = unpickedImages.shift();
// pick empty x, y on your table
// Insert the image tag im that <td></td>
} else {
clearInterval( loadAllImages );
}
}
You really don't need javascript to do this. If you specify the image sizes in the HTML or CSS, the browser will layout and display the page while loading the images, which will likely be loaded in parallel. It will then display them as soon as it can.
That way if users re-visit your site and have the images cached, they all show up immediately. If you have a script to load the images after a delay, you are making visitors wait for content unnecessarily and all their efforts to have a faster browser and pay for a fast internet connection has gone to waste.