I have three (3) javascripts that I am trying to execute in a specific order. My problem is that each javascript uses data set by the previous script. My first script, which executes on loading, gets data from an SQL database and copies it to the body of my web page. The next javascript needs some of this data to execute properly In order to execute the second script, I must wait not only until the previous script has completed execution but until the data has been loaded to the body of my web page so that it can be accessed by the second script. The relationship between the second and third scripts is similar. I've not been able to find any previous question and answer that addresses the use of data extracted by a previous script. Any help that you can offer will be very much appreciated. Here's an example of my latest attempt.
function myFunction()
{
document.getElementById("inputCounter").innerHTML = 1;
var recordCounter = document.getElementById("inputCounter");
var number = recordCounter.innerHTML;
querySQL(number);
document.onreadystatechange = function()
{
if (document.readystate == "complete")
{
getIPDetail('https://freegeoip.net/csv/');
}
};
}
myFunction() executes on loading of the page body. The first script called from myFuntion() is querySQL(number). The second script called from myFunction() is getIPDetail('https://freegeoip/csv/'). My problem is that detIPDetail... does not execute because it needs data that querySQL inserts into a div on the page body.
I was able to solve this problem through experimentation. In other words, I found the right positions in my code to put the javascript function calls so that my application flowed properly.
Related
I'm building a dynamic website that loads all pages inside a "body" div via jquery's load(). The problem is I have a script looped with setInterval inside the loaded PHP page, the reason being I want the script loaded only when that page is displayed. Now I discovered that the scripts keep running even after "leaving" the page (loading something else inside the div without refresh) and if I keep leaving / returning the loops stack up flooding my server with GET requests (from the javascript).
What's a good way to unload all JS once you leave the page? I could do a simple dummy var to not load scripts twice, but I would like to stop the loop after leaving the page because it's causing useless traffic and spouting console errors as elements it's supposed to fill are no longer there.
Sorry if this has already been asked, but it's pretty hard to come up with keywords for this.
1) why don't you try with clearInterval?
2) if you have a general (main) function a( ) { ... } doing something you can just override it with function a() { }; doing nothing
3) if you null the references to something it will be garbage collected
no code provided, so no more I can do to help you
This really sounds like you need to reevaluate your design. Either you need to drop ajax, or you need to not have collisions in you method names.
You can review this link: http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml
Which gives information on how to remove the javascript from the DOM. However, modern browsers will leave the code in memory on the browser.
Since you are not dealing with real page loads/unloads I would build a system that simulates an unload event.
var myUnload = (function () {
var queue = [],
myUnload = function () {
queue.forEach(function (unloadFunc) {
undloadFunc();
});
queue = [];
};
myUnload.add = function (unloadFunc) {
queue.push(unloadFunc);
};
return myUnload;
}());
The code that loads the new pages should just run myUnload() before it loads the new page in.
function loadPage(url) {
myUnload();
$('#page').load(url);
}
Any code that is loaded by a page can call myUnload.add() to register a cleanup function that should be run when a new page is loaded.
// some .js file that is loaded by a page
(function () {
var doSomething = function () {
// do something here
},
timer = setInterval(doSomething, 1000);
// register our cleanup callback with unload event system
myUnload.add(function () {
// since all of this code is isolated in an IIFE,
// clearing the timer will remove the last reference to
// doSomething and it will automatically be GCed
// This callback, the timer var and the enclosing IIFE
// will be GCed too when myUnload sets queue back to an empty array.
clearInterval(timer);
});
}());
I want to start out by saying I have found other similar question, but I don't understand how to execute with with my code as it isn't a function I created myself.
I have the following code:
$("#dataset").load('/hemaexplorerbeta/php/getDataset.php');
This loads some data and puts in in a dropdown.
Afterwards I'm calling the following to see if it's loaded when I need the list:
document.getElementById('dataset').value
Bot of these are in my document on load, and I need them to be. How can I make sure to get a value from "#dataset" AFTER the data has been downloaded? Yes, the data is fetched from a MySQL database.
You could pass function as second parameter.
Example:
$("#dataset").load('/hemaexplorerbeta/php/getDataset.php', function() {
var x = document.getElementById('dataset').value;
});
Use the callback function for .load:
$("#dataset").load('/hemaexplorerbeta/php/getDataset.php', function() {
// This gets executed when the content is loaded
$(this).show();
});
I am having some trouble with a bit of code. I have a function that does some stuff to some data, calls a remote system (activating a script on that system and passing in the data), and then makes another call to the same system to activate a different script (which acts on the data saved above). The problem is that the 1st call to the remote system appears to get lost in the execution.
This is being run in Safari, uses jquery; the function is tied to a button click, which is defined in the javascript code with an onclick function (i.e. it is not defined in the html button definition).
Here's a rough breakdown of the function (cleaned out for viewing purposes - I hope I left enough to make it clear):
function compareJSON() {
// loop through the objects, testing and changing data
// ...
dataSession=({ //build object for output });
$.each( dataSession.chapters , function( indexC, value ) {
//compare objects to some others, testing and changing data
});
// ...
//Call remote script on other system
urlString="url://blah.dee.com/Blar?script=SaveJSON&$JSONobject=";
window.location= urlString + JSON.stringify(dataSession);
//Call remote script on other system
window.location="url://blah.dee.com/Blar?script=EditJSON";
}
The last three lines of code are the two calls. It uses the window.location to actually trigger the remote system, passing the data through the URL. But I need BOTH scripts to get called and run. It appears that only the LAST script in the sequence ever gets run. If I switch them around it remains whatever is in last place.
Is there something about the window.location that doesn't actually process until the end of the function?
This script actually used to be a series of separate function calls, but I figured I was running into asynchronous execution that was causing the various script calls to not register. But once I put the code into this single function, it was still happening.
Any clues would be helpful.
Thanks,
J
Modifing the value of window.location is reserved exclusively for instances in which you'd like to cause a browser redirect.
It looks like you want to trigger a page request instead. You say you already have jQuery loaded, if so, you can trigger such a request using jQuery.get or a similar function.
For example:
// Loads the myscript.php page in the background
$.get('myscript.php');
// You can also pass data (in the form of an object as the second argument)
$.get('myscript.php', { name: "John", time: "2pm" });
I understand that JS is single threaded and synchronously executed. Therefore when i add a file to my browser head tag that file is executed as soon as its encountered. Then it goes to the next script tag & executes that file. My question is when I add a js file dynamically to an HTML head tag. How does the browser executes that file?
Is it like that the file is executed as soon as the file is loaded wherever the current execution is. Or is it that we can control how that file is executed?
When the script is loaded, it will be executed as soon as possible. That is, if some other javascript function is executing, like a clickhandler or whatever, that will be allowed to finish first - but this is a given because, as you say, in browsers JavaScript normally execute in a single thread.
You can't control that part of the script loading, but you could use this pattern - heavily inspired by JSONP:
inserted script:
(function () {
var module = {
init: function () {
/* ... */
}
}
ready(module); // hook into "parent script"
}());
script on main page:
function ready(o) {
// call init in loaded whenever you are ready for it...
setTimeout(function () { o.init(); }, 1000);
}
The key here is the ready function that is defined on your page, and called from the script you insert dynmaically. Instead of immediately starting to act, the script will only tell the parent page that it is loaded, and the parent page can then call back to the inserted scripts init function whenever it wants execution to start.
What happens when a JavaScript file is dynamically loaded ( very simplified, no checks ):
the file is loaded;
if there is function call e.g. doSomething() or (function(){...})(), the code is executed(of course you must have the definitions);
if there are only function definitions, nothing is happening until the function call.
See this example: 3 files are loaded, 2 are executed immediately, 1 is waiting the timeout.
Edit:
The script tag can be placed anywhere in the page. Actually it is better to be placed at the end of the page if the onload event is not used (yahoo speed tips).
With HTML5 JavaScript has web workers MDN MSDN wikipedia.
Considering a way to do this is
var js=document.createElement('script')
js.setAttribute("type","text/javascript")
js.setAttribute("src", filename)
document.getElementsByTagName("head")[0].appendChild(js);
// ^ However this technique has been pointed to be not so trusworthy (Read the link in the comment by Pomeh)
But answering your question
How does the browser executes that file?
As soon as the script is added to the DOM
Is it like that the file is executed as soon as the file is loaded wherever the current execution is?
Yes
Or is it that we can control how that file is executed?
Its better if you attach an onload event handler, rather than a nasty tricks.
Here is some code you can try to get an answer to your question.
<script>
var s = document.createElement('script'), f = 1;
s.src="http://code.jquery.com/jquery-1.7.2.js";
document.head.appendChild(s)
s.onload = function(){
console.log(2);
f = 0
}
while(f){
console.log(1);
}
</script>
This code should ideally print a 2 when the script loads, but if you notice, that never happens
Note: This WILL kill you browser!
I have some javascript placed inside of the jquery $(document).ready function. It searches for an anchor in the url, and then runs a separate function to display matching content.
The code executes if I place an alert inside of the if statement somewhere, but wont' run otherwise. I've stored all the anchor names in an array called 'anchorNameList', and am checking to see if the anchor in the URL exists.
I only want the function to run on the initial pageload, so I set the default value of 'currentAnchor' to 1000 and change it on each iteration.
if (currentAnchor == 1000 && document.location.hash.substring(1)) {
var checkForThisAnchor = document.location.hash.substring(1);
for (var j=0; j < anchorNameList.length; j++) {
if (anchorNameList[j] == checkForThisAnchor) {
expandMe(j);
}
}
}
In my experience, when a JavaScript problem magically fixes itself by adding an innocuous alert() somewhere, the source of the problem is typically an asynchronous request.
Under non-alert circumstances the async request hasn't finished yet. But by adding the alert, it has a chance to finish, and therefore allowing your code to travel a different code-path than it would have hit without the response of the complete asynchronous call.
I switched the onload event from jQuery's document.ready to window.ready. It worked properly about 30% of the time, so it was definitely a timing issue. It seemed the main JavaScript function on the page, which is retrieving list items, was running slowly. I just moved this entire expanding function to the end of that list retrieval function, so it just runs linearly.