My JSP is calling from a backbone application. In this JSP, I have CSS and script tags. But some how My script is not loading first in Backbone app. Same JSP is working in Java application, but not backbone application. I tried several things like keeping script in starting of the page and end of the page. But no luck.
Is there anyway I can execute JSP script first in backbone?
I would like to execute window.location.replace(url) first from below code when ever this jsp is loaded from backbone app. But currently it is loading CSS first and redirecting another page, this is causing page delay before redirecting
<script>
var entitle = "${Data.entitle}";
var optIn = "${OptIn}";
var isModel = ("${Data.Model}" == "true") ? false : true;
if(entitle == "true" && optIn == "IN") {
showWindow("some url", true);
}
function showWindow(url, isModel) {
if(isModel) {
var newWindow = window.open(url,'name','height=800, width=1200, resizable=yes, scrollbars=yes');
//popup is blocked
if(!newWindow){
//Some Logic
});
}
else if (window.focus) {
newWindow.focus();
}
}
else {
window.location.replace(url);
}
return false;
}
}
</script>
<style type="text/css">
// My styles
</style>
<div class="ticket">
// My HTML content
</div>
I have a JavaScript issue. I am using it to open an HTML web page in a new frame with the following function:
function openBranch(url) {
if (url == "Ping") {
top.folderFrame.location = "Ping.html"
} else if (url == "Logout") {
top.top.location = "Logout.html"
}
}
HTML usage:
<a href='javascript:openBranch("Ping")'>Ping</a>
I am unable to open another web page in my side menu bar once my Ping.html page is processed (Post request is used). My side menu bar is unable to open the new page and is not able to process any request.
It looks like the argument of the function changes the source of the document. If you want to just change the source, why don't you just do something like this:
<iframe src="test1.html" id="top"></iframe>
change to 1
change to 2
<script>
function change(val) {
if (val === 1) {
document.getElementById("top").src = "test1.html";
} else {
document.getElementById("top").src = "test2.html";
}
}
</script>
I have a link that I am trying to use the history API with - it is on the index page of my single-page-application:
<div id="main">
<div id="logoutlinkdiv">
Log out
</div>
</div>
When I click the link, a template is loaded into the #main div on my index page - and the URL changes to xxx/logout.php as it should. Here is the javascript responsible for the swap:
function supports_history_api() {
return !!(window.history && history.pushState);
}
function swapPage(href) {
var req = new XMLHttpRequest();
req.open("GET",
"templates/" + // ALL MY TEMPLATES ARE IN THIS DIRECTORY
href.split("/").pop(),
false);
req.send(null);
if (req.status == 200) {
document.getElementById("main").innerHTML = req.responseText;
return true;
}
return false;
}
function addClicker(link) {
link.addEventListener("click", function(e) {
e.preventDefault();
if (swapPage(link.href)) {
history.pushState(null, null, link.href);
}
}, true);
}
function setupHistoryClicks() {
addClicker(document.getElementById("logoutlinka"));
}
$(document).ready(function() {
window.onload = function() {
if (!supports_history_api()) { return; }
setupHistoryClicks();
window.setTimeout(function() {
window.addEventListener("popstate", function(e) {
swapPage(location.pathname);
}, false);
}, 1);
}
});
Everything works going forward, but when I click the back button the templates directory gets loaded into the #main div. This happens because location.pathname evaluates to /~Eamon/, and after the href.split("/").pop() - it is just an empty string. Therefore, the templates directory gets loaded because it is the directory pointed to in the swapPage function.
Obviously, all I want the program to do when I click the back button is reverse what just happened. In this case, it would mean swapping back in what I had in the #main div before the link was clicked. How do I "save" what I had before and load it upon clicking the back button? It may be something as simple as changing the directory structure...but I want my application to be an SPA.
Things I have read on the subject:
http://diveintohtml5.info/history.html (this is what I am modeling my code after)
http://www.sitepoint.com/an-overview-and-usage-of-javascript-history-api/
http://html5doctor.com/history-api/
http://dev.opera.com/articles/view/introducing-the-html5-history-api/
I have a feed from Coupons.com in the form of an iframe in my webpage and I want to run some JavaScript on this iframe. I want it to open on a page other than the default which is the first page.
If you go to http://www.coupons.com you can see the same feed I am working with.
Above the coupons is a list of pages 1-10. If you move the cursor over page 3 (for example) it reads javascript:GoToPage(3), which seems very simple, but I can't figure out how to script it and make that page 3 show up instead of page 1. Please help, thanks in advance-
they are reloading the page via ajax.
something like that (copied from another question that i answered):
HTML
JAVASCRIPT
function xmlhttp() {
var x;
try {
x = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
try {
x = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
x = new XMLHttpRequest();
} catch (e) {
x = false;
}
}
}
return x;
}
function page(idMenu) {
var http = xmlhttp();
if (!http) {
alert('XmlHttpRequest non supporté');
} else {
var url = 'pageOutput.php?pageNo=' + idMenu;
http.open('GET', url, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
document.getElementById('pageContent').innerHTML = http.responseText;
}
}
http.send();
}
}
now all you have left to do is create a PHP where you check whatever menu ID is called and echo page content according to $_GET['pageNo']. if you already got your pages on many PHP/HTML you may also just do include and echo them...
if(isset($_GET['pageNo'])){
//echo page code here according to $_GET['pageNo'] value
}else{
//echo main page
}
EDIT: You may also add URL param to refer the current page so the user can reload your page from a new window without having no params loaded...
EDIT: Iframe version will just reload the whole iframe, if you look when you change page you see the iframe blink. i strongly recommand using a div content, much easyer.
We are using jQuery thickbox to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using galleria a javascript library to display multiple pictures.
The problem seems to be that $(document).ready in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. $(document).ready seems to use the iframe parent ready state to decide if the iframe is ready.
If we extract the function called by document ready in a separate function and call it after a timeout of 100 ms. It works, but we can't take the chance in production with a slow computer.
$(document).ready(function() { setTimeout(ApplyGalleria, 100); });
My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?
I answered a similar question (see Javascript callback when IFRAME is finished loading?).
You can obtain control over the iframe load event with the following code:
function callIframe(url, callback) {
$(document.body).append('<IFRAME id="myId" ...>');
$('iframe#myId').attr('src', url);
$('iframe#myId').load(function() {
callback(this);
});
}
In dealing with iframes I found good enough to use load event instead of document ready event.
Using jQuery 1.3.2 the following worked for me:
$('iframe').ready(function() {
$('body', $('iframe').contents()).html('Hello World!');
});
REVISION:!
Actually the above code sometimes looks like it works in Firefox, never looks like it works in Opera.
Instead I implemented a polling solution for my purposes. Simplified down it looks like this:
$(function() {
function manipIframe() {
el = $('body', $('iframe').contents());
if (el.length != 1) {
setTimeout(manipIframe, 100);
return;
}
el.html('Hello World!');
}
manipIframe();
});
This doesn't require code in the called iframe pages. All code resides and executes from the parent frame/window.
In IFrames I usually solve this problem by putting a small script to the very end of the block:
<body>
The content of your IFrame
<script type="text/javascript">
//<![CDATA[
fireOnReadyEvent();
parent.IFrameLoaded();
//]]>
</script>
</body>
This work most of the time for me. Sometimes the simplest and most naive solution is the most appropriate.
Following DrJokepu's and David Murdoch idea I implemented a more complete version.
It requires jQuery on both the parent and iframe and the iframe to be in your control.
iframe code:
var iframe = window.frameElement;
if (iframe){
iframe.contentDocument = document;//normalization: some browsers don't set the contentDocument, only the contentWindow
var parent = window.parent;
$(parent.document).ready(function(){//wait for parent to make sure it has jQuery ready
var parent$ = parent.jQuery;
parent$(iframe).trigger("iframeloading");
$(function(){
parent$(iframe).trigger("iframeready");
});
$(window).load(function(){//kind of unnecessary, but here for completion
parent$(iframe).trigger("iframeloaded");
});
$(window).unload(function(e){//not possible to prevent default
parent$(iframe).trigger("iframeunloaded");
});
$(window).on("beforeunload",function(){
parent$(iframe).trigger("iframebeforeunload");
});
});
}
parent test code:
$(function(){
$("iframe").on("iframeloading iframeready iframeloaded iframebeforeunload iframeunloaded", function(e){
console.log(e.type);
});
});
Found the solution to the problem.
When you click on a thickbox link that open a iframe, it insert an iframe with an id of TB_iframeContent.
Instead of relying on the $(document).ready event in the iframe code, I just have to bind to the load event of the iframe in the parent document:
$('#TB_iframeContent', top.document).load(ApplyGalleria);
This code is in the iframe but binds to an event of a control in the parent document. It works in FireFox and IE.
This function from this answer is the best way to handle this as $.ready explicitly fails for iframes. Here's the decision not to support this.
The load event also doesn't fire if the iframe has already loaded. Very frustrating that this remains a problem in 2020!
function onIframeReady($i, successFn, errorFn) {
try {
const iCon = $i.first()[0].contentWindow,
bl = "about:blank",
compl = "complete";
const callCallback = () => {
try {
const $con = $i.contents();
if($con.length === 0) { // https://git.io/vV8yU
throw new Error("iframe inaccessible");
}
successFn($con);
} catch(e) { // accessing contents failed
errorFn();
}
};
const observeOnload = () => {
$i.on("load.jqueryMark", () => {
try {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href !== bl || src === bl || src === "") {
$i.off("load.jqueryMark");
callCallback();
}
} catch(e) {
errorFn();
}
});
};
if(iCon.document.readyState === compl) {
const src = $i.attr("src").trim(),
href = iCon.location.href;
if(href === bl && src !== bl && src !== "") {
observeOnload();
} else {
callCallback();
}
} else {
observeOnload();
}
} catch(e) {
errorFn();
}
}
Basically what others have already posted but IMHO a bit cleaner:
$('<iframe/>', {
src: 'https://example.com/',
load: function() {
alert("loaded")
}
}).appendTo('body');
Try this,
<iframe id="testframe" src="about:blank" onload="if (testframe.location.href != 'about:blank') testframe_loaded()"></iframe>
All you need to do then is create the JavaScript function testframe_loaded().
I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.
var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
url: url,
cache: true,
mimeType: 'application/pdf',
success: function () {
// display cached data
$(scroller).append('<embed type="application/pdf" src="' + url + '" />');
// hide spinner
$.mobile.hidePageLoadingMsg();
}
});
You have to set your http headers correctly as well.
HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";
This was the exact issue I ran into with our client. I created a little jquery plugin that seems to work for iframe readiness. It uses polling to check the iframe document readyState combined with the inner document url combined with the iframe source to make sure the iframe is in fact "ready".
The issue with "onload" is that you need access to the actual iframe being added to the DOM, if you don't then you need to try to catch the iframe loading which if it is cached then you may not. What I needed was a script that could be called anytime, and determine whether or not the iframe was "ready" or not.
Here's the question:
Holy grail for determining whether or not local iframe has loaded
and here's the jsfiddle I eventually came up with.
https://jsfiddle.net/q0smjkh5/10/
In the jsfiddle above, I am waiting for onload to append an iframe to the dom, then checking iframe's inner document's ready state - which should be cross domain because it's pointed to wikipedia - but Chrome seems to report "complete". The plug-in's iready method then gets called when the iframe is in fact ready. The callback tries to check the inner document's ready state again - this time reporting a cross domain request (which is correct) - anyway it seems to work for what I need and hope it helps others.
<script>
(function($, document, undefined) {
$.fn["iready"] = function(callback) {
var ifr = this.filter("iframe"),
arg = arguments,
src = this,
clc = null, // collection
lng = 50, // length of time to wait between intervals
ivl = -1, // interval id
chk = function(ifr) {
try {
var cnt = ifr.contents(),
doc = cnt[0],
src = ifr.attr("src"),
url = doc.URL;
switch (doc.readyState) {
case "complete":
if (!src || src === "about:blank") {
// we don't care about empty iframes
ifr.data("ready", "true");
} else if (!url || url === "about:blank") {
// empty document still needs loaded
ifr.data("ready", undefined);
} else {
// not an empty iframe and not an empty src
// should be loaded
ifr.data("ready", true);
}
break;
case "interactive":
ifr.data("ready", "true");
break;
case "loading":
default:
// still loading
break;
}
} catch (ignore) {
// as far as we're concerned the iframe is ready
// since we won't be able to access it cross domain
ifr.data("ready", "true");
}
return ifr.data("ready") === "true";
};
if (ifr.length) {
ifr.each(function() {
if (!$(this).data("ready")) {
// add to collection
clc = (clc) ? clc.add($(this)) : $(this);
}
});
if (clc) {
ivl = setInterval(function() {
var rd = true;
clc.each(function() {
if (!$(this).data("ready")) {
if (!chk($(this))) {
rd = false;
}
}
});
if (rd) {
clearInterval(ivl);
clc = null;
callback.apply(src, arg);
}
}, lng);
} else {
clc = null;
callback.apply(src, arg);
}
} else {
clc = null;
callback.apply(this, arguments);
}
return this;
};
}(jQuery, document));
</script>