When is window.location.href = url gets executed?
Very close to immediately. It tells the browser to start the process of loading the new page. The current page, and the code on it, will continue to run until the new page starts loading. More below.
I want $(window.document.body).append(compiledTemplate);
to be apended on the new Page which will get open.
You can't. The code in the current page cannot act on the next page. To act on the next page, you have to have your code in that page.
Your best bet is to have the current page supply information to the new page in some other way:
- Via a query string parameter
- Via local storage or session storage
- Via a cookie (blech)
...and then have code on the new page append the content.
If you're doing this in response to a user-generated event, you might be able to do this instead:
var wnd = window.open(url);
$(wnd).load(function() {
$(this).append(compiledTemplate);
});
...but it would open the URL in a new page (probably a new tab) and leave the current window open, and it would only work for pages from the same origin.
For instance, if you had this on a page: Live Example
<input type="button" id="the-button" value="Click">
<script>
(function() {
"use strict";
$("#the-button").click(function() {
var counter = 1;
location.href = "http://stackoverflow.com";
$("<p>Set, counter = " + counter + "</p>").appendTo(document.body);
setInterval(function() {
++counter;
$("<p>Counter = " + counter + "</p>").appendTo(document.body);
}, 50);
});
})();
</script>
When you clicked the button, you'd see the code after the line setting location.href
run, showing "Set, counter = 1" and then probably several more "counter = x" lines, and then eventually the page would be replaced by Stack Overflow. At that point, the code of the old page has been terminated. It can't do anything to the new page.