How to do asyncrhonous jQuery.get() before $(window).load()? - javascript

I want a SVG file to be loaded in a variable before $(window).load() will be fired.
I load the file using jQuery.get(). The problem is, that this function works asynchronously and by the time, when the SVG file is read, the $(window).load() is already invoked.
So I have following code:
var data;
$(document).ready(function () {
jQuery.get(
"my.svg",
function (_data) {
data = _data;
},
'text');
});
$(window).load( function () {
alert(data);
});
The alert will show "undefined". If it will be invoked later (after 5 seconds for example) then it will show the content of the SVG file.
Any suggestions? Thanks!

I agree that setInterval would probably be the solution you want IF you want to do stuff the hard way because you can never tell how long an AJAX request is going to take.
I would recommend restructuring your code to be more like this:
<script>
$(document).ready(function () {
//this can remain async: TRUE
jQuery.get(
"my.svg",
function (_data) {
//call function to do something to svg file
//if you are relying on the SVG to be there in order to call an action
//then why not wait for the SVG to load first and then call the action
svgAction(_data);
},
'text');
function svgAction(img_code){
//do something with img code now
}
});
</script>

Related

results of jquery $.get assignment to variable not usable in event listener

Can anyone identify the problem with this code and/or help to fix it?
I'm trying to preload html files, assign their html to variables, then inject them into a div after the user clicks a button.
I have it working successfully where the html files are loaded into the div on click, but I want to preload the html so the user doesn't have to wait for the external resource of the html file to load or not load if there is internet failure/ external resource fetching issues.
In the code, the alert successfully shows the html so I know at least that part works.
//IIFE
(function() {
// ^other stuff omitted
// start navButton behavior
var hatContent;
function doSomethingWithData(data) {
hatContent = data;
alert(data);
}
$.get('helpAndTips.html', doSomethingWithData);
function replaceNotebookContentWithVariable(content){
$("#usersNotebook").innerHTML = content;
}
document.getElementById('helpAndTipsButton').addEventListener("click", function(){
replaceNotebookContentWithVariable(hatContent);
}, false);
// end navButton behavior ____________________X
// other stuff omitted
})(); // end IIFE
Try this and see if it works better for you.
(function() {
//save the ajax deferred
var helpAndTips = $.get('helpAndTips.html');
function replaceNotebookContentWithVariable(content) {
$("#usersNotebook").innerHTML = content;
}
$('#helpAndTipsButton').on("click", function() {
//call the replace with the result of the deferred whenever it gets it
//if the deferred has already resolved this will happen immediately
helpAndTips.then(function(hatContent) {
replaceNotebookContentWithVariable(hatContent);
});
}, false);
})();
For some reason $('#usersNotebook').innerHTML = data; does not work, but document.getElementById('usersNotebook').innerHTML does work.
I never really managed to use helpAndTips like a variable and I think that is because fetching its data executes later in terms of event order than the code where I want to use the variable. However #Taplar your suggestion of using jquery's .then to fire a function after the data is fetched allowed me to add the "on cick" event listener with the acquired data inside of that "done" function which ensures the data is available due to it's place in the event chain. So the following code is working for me. Thanks!
`// start navButton behavior
function replaceNotebookContentWithVariable(content) {
document.getElementById('usersNotebook').innerHTML = content;
}
var helpAndTips = $.get('helpAndTips.html');
helpAndTips.then(function(data){
document.getElementById('helpAndTipsButton').addEventListener("click", function(){
replaceNotebookContentWithVariable(data);
}, false);
})
// end navButton behavior ____________________X`

Auto-refresh <div> text

This has been well answered several times, but being new to js I must be missing something basic.
My simple chat page works well, but refreshes only on manual call, and I want it to auto-refresh.
The php fetches the comment via POST, writes it to the log file (in the same directory), then writes the updated log file to the div.
<div id="show"><?php include 'LOG.txt' ; ?></div>
I adapted the following code from another post and tried it in header and in body, but it is not working.
<script type="text/javascript">
function doRefresh(){
$("#show").load("LOG.txt");
}
setInterval(function(){doRefresh()}, 5000);
</script>
What does this need?
Thank you.
Your code is mostly correct. However, you want to make sure that you only fire the function only at DOM ready, if your code is in the header. And of course you have to include jQuery.
NOTE: If you place your code just before </body> as it is, it should work.
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript">
function doRefresh(){
$("#show").load("LOG.txt");
}
$(function() {
setInterval(doRefresh, 5000);
});
</script>
setInterval() method will continue be calling until clearInterval() method is called, or when window is closed.
setTimeout() method calls a function after a specified number of milliseconds.
I'm used to treat such cases as the example below :
function doRefresh()
{
$("#show").load("LOG.txt");
setTimeout(function() {
doRefresh();
}, 2000);
}
$(document).ready(function () {
doRefresh();
});
By calling function itself like this example, with the setTimeout() method, it will be called every 2 seconds.
See my jsfiddle version
try Via Ajax
function doRefresh(){
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
setTimeout(function() {
doRefresh();
}, 2000);
}
$(document).ready(function () {
doRefresh();
});
Check console for Error.
https://stackoverflow.com/a/6470614/6079755

Load one time beside the $(document).ready(...) ? Jquery

I have a problem with triggering a function which needs to be loaded only one time.But I don't want to put it into:
jQuery(document).ready(function ($) {
});
I want to run it separate.
I have tried:
jQuery(document).one(function () {
myfunction();
});
and some other stuff.
But couldn't solve it.
UPDATE:
I have my webservice on ready():
jQuery(document).ready(function ($) {
PageMethods.myWebSer(suc, fail);
});
function suc(){
//I want to run my function here , but only one time
//Examplle
//jQuery(document).one(function () {
// myfunction();
// });
}
Thank You
Just add another ready or load function : you may have as many as you want, they will all be called in order :
jQuery(document).ready(function() {
// this will be run
});
jQuery(document).ready(function() {
// and this one too (after the other one)
});
It you want it to run onload use:
jQuery(window).load(function () {
// run
});
Keep in mind that ready fires before load.

Javascript loaded check through jquery getscript

I want to load a Javascript file on the click event instead of loading at the page load event, for performance reasons.
Is there anyway to know that particular if javascript is already loaded?
Right now I am maintaining a global variable to check the 'loaded' event
var javascriptLoaded=false
if (!javascriptLoaded)
$.getScript('/scripts/test.js', function() {
javascriptLoaded = true;
setTimeout(function() {
callSomeFunctionhere();
}, 1000);
});
Is there any better way of doing this?
Yes. What you want to do is use the success callback. A call back method which will only be called once the ajax request to load the script has successfully finished. For example this is equivalent:
$.ajax({
url: "/myscript.js",
dataType: "script",
success: function(){
scriptLoaded = true;
//do some more stuff now that the script is loaded
}
failure: function(){
scriptLoaded = false;
}
});
A simple way to check if a script has been loaded is to see if that script is callable:
if($.fn.foo == undefined) {
$.getScript("/path/to/script/foo.js", function() {
// success
});
}

How can I achieve $(document).ready type behavior for AJAX content?

$(document).ready(handler) executes once the DOM is fully loaded. If content is later added to the page using AJAX, which contains a $(document).ready(handler) function, this function is executed immediately, per the jQuery API. Additionally, .ready can only be called on a jQuery object matching the current document.
This is not what I want, however :)
How can I achieve this .ready type of functionality for data loaded via AJAX after .ready has already fired, in a cross-browser compliant manner?
EDIT:
Here's a very simplified example. I do have a problem I'm trying to solve, but I'm more interested in understanding the way to do this properly.
Basically, the .ready function in ajaxPage.html is firing before importantDependency.js is completely loaded, so the first load of ajaxPage, importantDependency is missing, but subsequent loads see it.
index.html
...
<script type="text/javascript">
$(document).ready(function() {
alert("The document is ready");
$('#myButton').click(function() {
$('<div></div>').dialog({
open: function () {
$(this).load('ajaxPage.html');
}
});
});
});
</script>
...
ajaxPage.html
...
<script type="text/javascript" src="importantDependency.js"></script>
<script type="text/javascript">
$(document).ready() {
$('#thing').leverageImportantDependency();
});
</script>
...
EDIT 2:
I want to do this FROM the loaded content, not from the page calling the content. Modifying the calling page means duplicating code in every instance where this is called. I'd like the behavior to be attached to the content, not the page calling it.
Generally, you will want to do something like this:
$("#container").load(function(html) {
// container has been filled up, and is
// ready for JS processing
doSomethingWithNewContent();
});
That is to say, fire off something once the content has been replaced, by utilizing the appropriate ajax callback. Other examples include:
$.get("foo.html", function(html) {
$("#container").html(html);
$("#container").find(".foo").fancyThing();
});
$.ajax({
url: 'foo.html',
type: 'post',
success: function(html) {
$("#container").html(html).find(".foo").hide();
}
});
See:
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.load/
EDIT: From what I understand from your edit, you want attach something, such as a an event handler or a plugin to some elements that keep getting replaced. There are a few ways to do this:
In the success callbacks, as
demonstrated above.
Using .live or
.delegate.
Using .liveQuery.
I'm not sure if I get your question, but when you have retrieved the data, you simply do whatever you want with it in the success handler of the ajax call:
$.ajax({
url: pageUrl,
success: function (data) {
$(".someContainer").html(data);
// TODO: This is your ready handler for the new content
}
});
You could use the complete property of an JQuery Ajax call. The complete function is called after success or error.
$.ajax({
url: "foo",
complete: function({
// I'm done
}
});
See: http://api.jquery.com/jQuery.ajax/

Categories