4

I have a Javascript file that is split into to two parts. The first part of the code ends by refreshing the current page. I would like to try to get the second part of the code to execute as soon as the page reloads, but I am having trouble finding a way to implement this. I pretty much want a way to do

window.onload = someFunction() 

except that it activates the function after reloading the page due to the first part of the Javascript. Is there an effective way to do this?

3
  • Add Javascript at the end of page. Commented Dec 15, 2011 at 10:36
  • window.onload = someFunction? Commented Dec 15, 2011 at 10:49
  • A little bit more code can make the question a bit more clear . Commented Dec 15, 2011 at 22:58

3 Answers 3

3

You could do that using Jquery. This is executed on page loading

$(function() {
    callMyFunction()
});
Sign up to request clarification or add additional context in comments.

Comments

2

Use

document.onload = somefunction() Instead . This will get executed immediately after the DOM loads .

You can also use the jQuery to do the same like

$(document).ready(function(){
    somefunction();
});

Comments

1

The only way I can think of is to add query string value when refreshing, then read that value and act upon it.

You can use such code:

function ParseQueryString() {
    var result = [];
    var strQS = window.location.href;
    var index = strQS.indexOf("?");
    if (index > 0) {
        var temp = strQS.split("?");
        var arrData = temp[1].split("&");
        for (var i = 0; i < arrData.length; i++) {
            temp = arrData[i].split("=");
            var key = temp[0];
            var value = temp.length > 0 ? temp[1] : "";
            result[key] = value;
        }
    }
    return result;
}

window.onload = function WindowLoad() {
    var QS = ParseQueryString();
    var reloaded = QS["reloaded"];
    if (reloaded === "1") {
        //execute second part of code
    }
}

Then when reloading, redirect to same page adding ?reloaded=1 otherwise (if this flag is already raised) don't refresh the page again to avoid infinite loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.