JS function execution order - javascript

I have two pages namely Parent.xhtml(controls the layout) and Child.xhtml(displays the content). Child page is included in the Parent page by using <iframe> tag.
I need to implement an onload functionality by using javascript. Before that, I want to know in which order the javascript functions will execute?
Will the Parent page js function execute first? or Child page js function will execute first?
Awaiting your answers.! Thanks in advance

According to a previous answer, browsers might not wait for iframes to load before firing the onload event on the parent window. You can't make assumptions on which one will complete first - there's the possibility of a race condition going on there, so either one could finish first.
One solution might be to write a function that waits until it's been called a certain number of times before executing:
var runs = 0;
function onLoad() {
if (++runs < 2) return;
// put code to execute once both have loaded
}
Then in HTML:
<body onload="onLoad();">
.....
<iframe onload="onLoad();">
Alternatively, set the URL of the iframe in the onload handler of the parent window.

Related

Can I use JavaScript that is called on page load to modify other elements on the page?

I work in advertising. I have a client who has a tracking tag implemented on page load on their advertiser's site. The tracking tag is just a script that calls the JavaScript contained within.
The client is running into a dilemma because they want to trigger another tag when a specific button on the page is clicked on. I don't know the reasoning, but the advertiser's web developers said that it would take them weeks to make the change and the client is aiming to get the tracking set up as soon as possible.
The client's only means of access to the advertiser's page is through the tracking tag called on page load. The client wants to call some JavaScript from the tag that fires on page load that executes a certain function with the button is clicked on. I guess this would involve writing some JavaScript to the document so that it is usable when the button is clicked on.
Questions:
1) Is this possible? In other words, can I take some JavaScript that executes on page load and use it to modify elements on the page?
2) If the button already has another onclick function attached, can we add a second one? The button has a 'class' attribute attached, so could I develop some JavaScript to search for that class attribute and append a second onclick to it? Or would that override the first one?
Note: I cannot use document.write. Would document.appendchild work? Any tips would be appreciated.
To clarify what I want to do again:
1) Trigger JavaScript file on page load.
2) From within that JavaScript file, send a function to the document/page, and attach the reference to that function to a button with a specific class attribute on the page via an onclick attribute.
3) I do not want to override any existing onclick function on the button.
Thanks,
Update:
Here's what I have so far.
<html>
<head>
<script>
function myFunction (){
//do something
}
document.getElementsByClassName('test').onclick = myFunction();
</script>
</head>
<body>
<button class="test"> Submit Request </button>
</body>
</html>
I want to make it so that when the script in the header loads, myFunction is called from the button with class "test". Am I on the right track?
Update 2: Would using setAttribute work?
<html>
<body>
<script>
function myFunction (){
//do something
}
document.getElementsByClassName('test')[0].setAttribute("onclick", "myFunction()");
</script>
<button class="test"> Submit Request </button>
</body>
</html>

Re-execute js on back without reloading the whole page

Is there a way to re-execute JS without refreshing a page?
Say if I have a parent page and an inside page. When the inside page gets called, it gets called via ajax, replacing the content of the parent page. When user clicks back, I would like to navigate them back to the parent page without having to reload the page. But, the parent page UI relies on javascript so after they click back, I would like to re-execute the parent page's javascript. Is this possible?
Edit: Here is some code. I wrap my code in a function but where and how would you call this function?
function executeGlobJs() {
alert("js reload success");
}
You could use the html5 history-api:
In your click-handler you'll call the pushState-method, stat stores the current state for later reuse:
$(document).on('click', 'a.link', function () {
// some ajax magic here to load the page content
// plus something that replaces the content...
// execute your custom javascript stuff that should be called again
executeGlobJs()
// replace the browser-url to the new url
// maybe a link where the user has clicked
history.pushState(data, title, url);
})
...later if the user browses back:
$(window).on('popstate', function () {
// the user has navigated back,
// load the content again (either via ajax or from an cache-object)
// execute your custom stuff here...
executeGlobJs()
})
This is a pretty simple example and of course not perfect!
You should read more about it here:
https://css-tricks.com/using-the-html5-history-api/
https://developer.mozilla.org/en-US/docs/Web/API/History_API
For the ajax and DOM-related parts, you should need to learn a bit about jQuery http://api.jquery.com/jquery.ajax/. (It's all about the magic dollar sign)
Another option would be the hashchange-event, if you've to support older browsers...
You can encapsulate all your javascript into a function, and call this function on page load.
And eventually this will give you control of re-executing entire javascript without reloading the page.
This is common practise when you use any concat utility (eg. Gulp)
If you want to reload the script files as if it would be on a page reload, habe a look at this.
For all other script functions needed, just create a wrapper function as #s4n989 and #Rudolf Manusadzhyan wrote it. Then execute that function when you need to reinit your page.
I'm having the same problem I don't use jquery.
I don't have a solution yet. I think that your problem is that it doesn't read all the document.getelements after you add content, so my idea is to put all the element declarations in a function. And than after the ajax call ends to call the function to get all the elements again.
So it might be something like that
Func getElems(){
const elem= document.getelementsby...
Const elem.....
At the end of the js file make a call for
the function
getelems()
And than at the end of the event of the
ajax call. Just call the function again.
Sorry that is something that comes to my mind on the fly while reading and thinking on the problem i have too:).
Hope it helped I will try it too when I will be on the computer :)
I believe you are looking for a function called
.preventDefault();
Here's a link to better explain what it does - https://api.jquery.com/event.preventdefault/
Hope this helps!
EDIT:
By the way, if you want to execute the JS on back you can wrap the script inside of
$('.your-div').on('load', function(e) {
e.preventDefault();
//your JavaScript goes here
}

Adding a document.write in the load function of a new dashcode template causes rest of JS not to get generated

I started a new custom template for safari in dashcode ("This template creates a blank web application, ready for customizing."). It auto generates a function load in main.js that is called from the body in index.html:
function load() {
dashcode.setupParts();
}
I added some JS code after the function which seems to execute as part of the HEAD when i run. I also added an onclick event in the body of index.html:
<body onload="load()";>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
I also got the the button for it when I run.
Whenever I add a document.write call to the function load (which should just execute on load before the button is displayed) nothing else gets generated when I run. In other words whenever load becomes:
function load() {
dashcode.setupParts();
document.write("LOADING");
}
none of the javascript that i added after the function gets displayed. Also the onclick button that i added in the body doesn't appear.
Does anybody have an explanation for this behavior?
calling document.write() after page load will overwrite the current page - javascript, html, everything - which is why it is so frowned upon generally. Look at DOM methods or innerHTML manipulation for alternatives.

JavaScript heap size ever increasing with AJAX calls

I am designing a web application, and the app requires that I use AJAX to navigate pages, so the same frame is static, but the inner content changes, like
$(".nav > div").on('click',function(){
var id = $(this).attr('id');
$(".active").removeClass("active");
$(this).addClass("active");
$("#main").load("/page" + id + ".html");
});
which will load page1.html, following me clicking on the element with the id '1', for example.
I then use
$(document).ajaxComplete(function() {...javascript...});
to run the rest of my script which will be interacting with the inner content. My script contains numerous functions like
$('#fade').on('click', function() {
$('#zoom').removeClass('grow').addClass('shrink');
which interact with unqiue id's, all of which are similar in each of the '/page[number].html' files.
My script runs fine if I run it on an entirely static page, but as soon as I start introducing the AJAX element of reloading the html in the inner frame, the website gets slower and slower every time I make an AJAX call - by using the .nav bar - until a crash. The javascript heap size seems to increase almost exponentially, see:
http://imgur.com/0mvoOjA
Not only the js heap size is ever increasing, but it also seems 'paint' is taking up a lot of memory. Each page I am loading a new, fairly high res image, could this be related?
I am fairly new to AJAX calls so any pointers would be appreciated! Thanks
It's likely that you're creating event handlers with $().on on the other pages and you aren't explicitly removing them before you navigate to another page.
$(element).on(event, function() {
// ...
});
When you make an event listener like this jQuery maintains a reference to the function, meaning it can't be garbage collected. Every time you navigate to a new page, you create more event handlers that can't be automatically removed.
function eventHandler() {
// ...
}
// when the page is loaded
$(element).on(event, eventHandler);
// just before you leave
$(element).off(event, eventHandler);
Better still, when you know there only needs to be one interaction with the element before you'll navigate away, you can use one, to create an event listener that will be called only once before it is automatically dereferenced.
$(element).one(event, eventHandler);
// don't worry about removing these handlers
How you structure this code is best determined by your existing application architecture.
You need to unbind the events. If not, you are binding and binding events to your element instead of override it. You can do it with $('#yourElement').unbind('click');

Callback after PJAX request is finished and has downloaded assets

An application of mine uses PJAX style navigation, which means that rather than loading the full page, we use AJAX to load a partial page and then use the HTML5 history/pushState API to update the browsing history.
Previously I was using the window.onload event to measure end user page loading times and I want to be able to record these times with the PJAX page loads, the problem is that this event does not fire after PJAX loads.
I have access to a pjax:end event which fires once the PJAX request is complete, but this is fired before all assets have finished downloading. I would like to be able to instrument the complete time it takes to download the page including the time to download extra (images/scripts) assets.
Is this possible? Is there a callback i'm missing or some magic that will allow me to measure the complete request time?
I realised that I only need to wait for images (not scripts).
A friend pointed me to this jQuery plugin: https://github.com/alexanderdickson/waitForImages
I'm using this code to trigger the onload event:
$('#main-inner').waitForImages(function() {
window.onload();
});
I don't think there is a specific event for a block of HTML loaded asyncronously. I think the best option is to attach your html, find each img and script, then bind to the load event (assuming jQuery) for each of them. When the number of loads equals the number of elements you found, then everything is loaded. I hope this helps.
var start = new Date().getTime(),
elems = $('#my-div').append(html).find('img, script'),
count = 0;
elems.on('load', function () {
if (++count === elems.length) {
var diff = new Date().getTime() - start;
}
});

Categories