window.location.reload complete? - javascript

I call
window.location.reload(false)
in a javascript method to update the page. I have additional javascript calls after this call. Is there a way to know when window.location.reload(false) has completed running before calling the additional javascript calls?

You simply have to provide a function to onload : a reload isn't different from a load.
window.onload = function() { // ...

Your line of code window.location.reload(false) causes the browser to reload the current page - no script after this statement will be executed ....
You could set a cookie on first load - then on subsequent loads check for the existence of the cookie and perform an action ... pseudo code :
onload = check cookie
if cookie is present
run function
else
set cookie
reload
You could check the time on the cookie and choose to execute the function after a period of time (1 hour for example) has passed ....

I use the hashtag to set variables that tells me if the page is reloaded or not. You could do something like this:
// Get the hash of the page
var hashstring = window.location.hash.substring(1);
var found = false;
// Do a hash exist?
if (hashstring.length > 0)
{
// Split the hash by '&'-sign (in case you have more variables in the hash, as I have)
var a = hashstring.split("&");
// Loop through the values
for (i = 0; i < a.length; i++)
{
// Split the string by '=' (key=value format)
var b = a[i].split("=");
// If the key is 'reloaded' (which tells us if the page is reloaded)
if(b[0] == 'reloaded')
{
found = true;
}
}
}
if(!found)
{
location.hash = 'reloaded=true';
window.location.reload();
}
// Do other stuff, this will only be executed if the page has been reloaded
I've put the code that finds a variable in the hash in a seperate function in my project, but fot simplicity I just added it here above. This makes it possible to determine if the page has been reloaded, and run code only if it has.

Related

Sometimes, jQuery only updates elements on first page load

I'm learning javascript by creating a program which requests an API and dispays various properties (price in this example) to html. I have a few questions about my code and some problems I've been facing.
1). I have a bunch of $.getJSON functions corresponding to each value that I want to retrieve. I put them all in a a single 2 min. timer. When the page FIRST loads, however, some of the html elements fail to load at all. But if I refresh the page, they sometimes do load. If I refresh again, they might not load at all again. Every time I refresh, there's like a 10% chance of that particular function not inserting the content in the element. If it does load and I leave the page open, it will correctly function (update its value and html element every 2 mins and add/remove the green and red classes). If it doesn't load and I leave the page open, it will correctly function in 2 mins when the 2nd api request is made. I have already tested that the variables have some value (are not null) before and after each $('#price').text('$' + price);.
Here's an example of a function that does that:
var tempPrice;
var myVar = setInterval(myTimer, 1200000);
myTimer();
function myTimer() {
$.getJSON(link, function (json) {
$.each(json, function (index, value) {
if (value.id == "price") {
var price = value.price_eur;
if (!tempPrice) {
$('#price').text('$' + price);
tempPrice = parseFloat(price);
}
if (parseFloat(price) !== tempPrice) {
$('#price').text('$' + price).removeClass();
if (parseFloat(price) > tempPrice) {
setTimeout(function () {
$('#price').addClass("green");
}, 1);
} else {
setTimeout(function () {
$('#price').addClass("red");
}, 1);
}
tempPrice = parseFloat(price);
}
}
});
});
// Many more $.getJSON functions below...
}
If I run this function alone on either jsfiddle or my dev server (flask), it works fine. It only breaks down when I use it in conjunction with more api requests. If I remember correctly, I didn't have this problem before when I used to have a separate timer for each $.getJSON function and put each in its own <script> tag directly in html.
2) I know I can loop through the json instead of using $.each. How else can I improve the code?
1
As for the problem you're having with the inconsistent behavior of the initial page loading, it's because you are executing JavaScript before giving the browser the time to load the page fully first. You can solve this simply by waiting for the page the load, and then executing your code.
Example in jQuery:
$(document).ready(function() {
// Page is loaded, execute code...
});
2
To help you improve the way you're handling the supplied JSON data, a sample of the data would be useful.

Injection of scripts dynamically at button press

A button on my web page upon clicking performs the following action i.e. Injects the script into the page
function InjectToolbar() {
var script = document.createElement('script');
scriptFarfalla.src = 'some_Path'
document.getElementsByTagName('head')[0].appendChild(script);
}
.
.
.
.
.
.
It successfully performs the action desired. But when I reload the page the script is lost
Is there any method/technique with which I can buffer the button's click
Like a toggle button
Toggle.....> script injected
Toggle.....> script detached
Everything that happens in javascript is reset when you leave a page (and return to it). So you need a way to store whether something is loaded or not. This depends on how long you want this to be "saved"/"remembered". There are a few options for you to save this information - Cookies, HTML5 localStorage, HTML5 sessionStorage, and any server session usage you have available (if applicable). So if you want to implement something like this, you now need code onload of your page that checks the specific storage to see if you have set it. If so, inject the script. Here's what I mean:
window.onload = function () {
if (checkIfInjected()) {
scriptInjection(true);
}
}
function toggleInjection() {
if (checkIfInjected()) {
scriptInjection(false);
} else {
scriptInjection(true);
}
}
function scriptInjection(inject) {
if (inject == true) {
var script = document.createElement('script');
script.src = 'some_Path';
script.id = 'injected_script_id';
document.getElementsByTagName('head')[0].appendChild(script);
// Set the storage to say that script is injected
} else {
var the_script = document.getElementById("injected_script_id");
the_script.parentNode.removeChild(the_script);
the_script = null;
// Set the storage to say that script has been removed (or remove from storage altogether)
}
}
function checkIfInjected() {
// The following syntax is wrong for anything - you need to use the correct getter for the storage type you use
return storage.contains("script_injected");
}
<input type="button" id="button1" onclick="toggleInjection();" />
Now it is up to you to determine what storage type you want because they all do different things, including how things are stored, what they are stored for, and how long they are stored for.
You can use a cookie to store the scripts you've injected, and then re-inject them on page load. Cookies and the newer local storage are the usual ways of storing state on the client.

How to make my function to be page specific or div id specific?

I am writing javascript to my web pages, but there is a number of functions and loops, that i think are running in all pages, so the first one is running and failing on the second page. Because of this, the javascript function on the second page is not running.
Can anyone give me an idea of how to create page-specific functions or check the availability of an id? I don't use any frameworks.
thanks in advance.
my javascript code is :
window.onload = function(){
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
function animeYellowBar(num){
setTimeout(function(){
yellows[num].style.left = "0";
if(num == yellows.length-1){
setTimeout(function(){
signUp.style.webkitTransform = "scale(1)";
},num * 250);
}
}, num * 500);
}
for (var i = 0; i < yellows.length; i++){
animeYellowBar(i);
}
alert("alert second page");
}
in this code, the alert message not working on second page. any idea?
If I understand you correctly, you have a javascript function, that you want to attach to an event from a specific div element in your page.
a) Include an event directly to you HTML page, something like this:
<div id="element" onclick="some_function();">Text is here</div>
b) Use a javascript function (add this code between <script> tag):
window.onload = function() {
document.getElementById("element").setAttribute("onclick", "some_function()")
}
The best way would be to only include those scripts on the pages which need them. Why waste time loading and parsing scripts you don't need?
If you must keep them on every page, put your functions in an if statement and check for something unique to the page that needs them (such as a form element or field ID).
Update
In response to your comment:
You have to code more defensively. You are attempting to make use of the magazine-brief and signup-link elements before you have made certain that they exist. Never trust that the proper element was returned - always check that it was before attempting to use that element.
I suggest checking your vars like so:
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
var signUp = document.getElementById('signup-link');
if (yellows != 'undefined' && signUp != undefined)
{
function animeYellowBar(num)
{
//...
}
}

How to run a javascript function using the # in the url?

hi this all started when i ran a function (lets call it loadround) that altered the innerHTML of an iframe. now once loadframe was loaded there were links in the iframe that once clicked would change the iframe page. the only problem is when i click the back button the loadround page was gone. i've thought about this numerous times to no avail. so i tried this code.
loadround
then
function loadround(a,b){
window.location.hash = "#loadround('"+a+"','"+b+"')";
var code = "<(h2)>"+a+"</(h2)><(h2)>"+b+"</(h2)>"
var iFrame = document.getElementById('iframe');
var iFrameBody;
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0]
iFrameBody.innerHTML = code;
}
(the brackets in the h2 are intentional)
then i would try to reload the function by possibly an onload function but for now i was testing with a simple href as followed.
function check(){
var func = location.hash.replace(/#/, '')
void(func);
}
check
unfortunately the check code doesn't work and im almost certain there is an easier way of doing this. i tried changing the src of the iframe instead of the innerhtml and there was the same problem. thanks in advance
The modern browsers are starting to support the event window.onhashchange
In the meantime you can use the workaround proposed by Lekensteyn or maybe you can find something useful here: JavaScript/jQuery - onhashchange event workaround
You are misunderstanding the function void, which just make sure the return value is undefined. That prevents the browser from navigating away when you put it in a link. You can test that yourself by pasting the next addresses in your browser:
javascript:1 // note: return value 1, browser will print "1" on screen
javascript:void(1) // note: undefined return value, browser won't navigate away
It's strongly discouraged to execute the hash part as Javascript, as it's vulnerable to XSS without proper validating it. You should watch the hash part, and on modification, do something.
An example; watch every 50 milliseconds for modifications in the hash part, and insert in a element with ID targetElement an heading with the hash part. If the hash part is not valid, replace the current entry with home.
var oldHash = '';
function watchHash(){
// strip the first character (#) from location.hash
var newHash = location.hash.substr(1);
if (oldHash != newHash) {
// assume that the parameter are alphanumeric characters or digits
var validated = newHash.match(/^(\w+)$/);
// make sure the hash is valid
if (validated) {
// usually, you would do a HTTP request and use the parameter
var code = "<h1>" + validated[1] + "</h1>";
var element = document.getElementById("targetElement");
element.innerHTML = code;
} else {
// invalid hash, redirect to #home, without creating a new history entry
location.replace("#home");
}
// and set the new state
oldHash = newHash;
}
}
// periodically (every 50 ms) watch for modification in the hash part
setInterval(watchHash, 50);
HTML code:
Home
About Me
Contact
<div id="targetElement">
<!-- HTML will be inserted here -->
</div>

deleting cookie at the end of a process

I am using the following plug in for cookies in jQuery:
https://code.google.com/p/cookies/
The issue i am having is not with the plugin but when and how to delete the cookie at the end of a quoting process.
The site i am using this on is a six step online quote and buy process.
There is Omniture event serialisation sitestat tracking applied to some of the pages. This event serialisation has to include the name of the event and a random number of which i create.
I have a generic function for this which i call at the bottom of the page like so:
serialEvent('event21:', 'payment');
Here is the function:
function serialEvent(eventNumber, eventName) {
var sessionID = jaaulde.utils.cookies.get('sessionID');
var remLength = 20 - eventName.length;
var remSession = sessionID.substr(sessionID.length - remLength, remLength);
var eventName = eventName + remSession;
s.events = eventNumber + eventName;
}
I need to delete the cookie at the end of the process, the Thank you page but i also need the cookie 'sessionID' for the 'serialEvent' function.
As the function is called at the bottom of the page should i just write the cookie delete after it? Is that robust enough?
I need to be sure that the function has successfully been called before the cookie is deleted.
The code for deleting the cookie is quite simple:
jaaulde.utils.cookies.del('sessionID');
Thanks :)
There's no asynchronous or timer-delayed callback functions called in serialEvent function so you can either
Put it at the end of the function before the closing bracket,
or
Put it after serialEvent('event21:', 'payment');.
Javascript executes synchronously, so you can be sure that the cookie is only deleted when you are finished with it.
you can delete the cookie at the end of the process as well as in window.onUnload event to make sure that the cookie is cleared even if you are closing the window before the process completes.
function serialEvent(eventNumber, eventName)
{
var ok = false;
try
{
var sessionID = jaaulde.utils.cookies.get('sessionID');
var remLength = 20 - eventName.length;
var remSession = sessionID.substr(sessionID.length - remLength, remLength);
var eventName = eventName + remSession;
s.events = eventNumber + eventName;
ok = true;
}
catch(e)
{
// todo: error handling (what has gone wrong?)
ok = false;
}
return ok;
}
This way you can find out if the function is called correctly. ok will only be true if the whole function is executed correctly.

Categories