Order of self-invoking function in page load events - javascript/html - javascript

I'm looking to find out the order at which a self-invoking js function takes place in terms of the order of events in a page load. I've been googling all over for an answer to this but haven't found anything definitive.
And as for what this actually applies to, I'm adjusting the height of an outer element based on the height of one of it's inner elements (which will vary depending on length of text and screen width)
var text_elem = document.getElementById('text_elem');
var textElemHeight = text_elem.offsetHeight;
var newBkgdHeight = 96 + textElemHeight;
document.getElementById('background').style.height = newBkgdHeight + "px";
as of now this block is being executed in a self-invoked function as opposed to an onload event since with an onload event there's a weird effect where the height adjusts a second or 2 after the page has loaded, but just wanted to be sure that using a self-invoked function is safe and that there's no chance of the code within it being executed before the HTML DOM loads.
EDIT:
Just as a note, this is working properly using a self-invoking function or IIFE, I just want to make sure it's safe and will consistently work, and be able to explain this better to a colleague if it is.
Here is the relevant code for this situation:
<style type="text/css">
#background {
height: 150px;
}
</style>
......
......
<div id="background">
<div id="text_elem">
${text loaded from somewhere else}
</div>
</div>
......
......
<script>
(function() {
var text_elem = document.getElementById('text_elem');
var textElemHeight = text_elem.offsetHeight;
var newBkgdHeight = 96 + textElemHeight;
document.getElementById('background').style.height = newBkgdHeight + "px";
})();
</script>

Your IIFE will execute as soon as the <script> block containing it is loaded.
Since it's located at the end of the HTML, it will be executed after all the earlier HTML is loaded into the DOM.
The execution time is no different than if you hadn't put it in an IIFE at all, but just wrote it as top-level JavaScript code. The only difference from putting it in an IIFE is that the variables are local rather than global.

Related

Why resize function is not working on iframe

im triying to figure out why my resize function is not working. I tried to change values of style.height but seems to not work anyways. I'm newbie at JavaScript so possibly will be an easy solution.
<script>
function resizeIframe(newHeight) {
document.getElementById('cursoFrame').style.height = parseInt(newHeight, 10) + 70 + 'px';
}
</script>
<iframe id="cursoFrame" class="frames" src="http://www.google.es" onload="parent.scroll(0,0);">
In order for the function to work, you need to call it either within the iframe onload or within the script.
Currently your script initialises the function, but you are not using it anywhere.
If you add another script block below iframe block, and type within that script block:
<script>
resizeIframe(400);
</script>
This should then call the function and change the height of your iframe.

Replace text on webpage using javascript

I am trying to replace some text on my sites page using javascript. I must use javascript because the replacement is dependent on the site resolution. However I found that the code bellow doesn't work. Why is it? Does similar things work on iphone (these javascript functions)? Thanks.
<SCRIPT language="JavaScript">
<!--
if ((screen.width<=500))
{
document.body.innerHTML = document.body.innerHTML.replace('text to replace', 'replacement');
}
//-->
</SCRIPT>
The screen property does not have a resize cause it's like they built it in the factory :)
You're probably interested in window.innerWidth
probably you're also interested in listening for a resize event so here you go:
function doOnResize() {
var winW = window.innerWidth;
if(winW <= 500) {
document.body.innerHTML = document.body.innerHTML.replace('text to replace', 'replacement');
}
}
doOnResize(); // Do it as soon as you can
window.addEventListener("resize", doOnResize); // and on window resize
Also make sure to place the above <script> right before the closing </body> tag. This will make sure that the JS parser is in known about the DOM content before searching and replacing text.
Your code does not work because it is executed before the DOM is ready.
window.onload = function() { /* Your code here */ };
This will make sure the DOM is ready and everything is loaded.
What about using css and js (well, jquery would probably be best) to change the display attribute of the element on the event that triggers the text change?

onload function init not found

I'm encountering a strange issue. I am developing a books application and using javascript onload. I read somewhere that its best to include your javascript at the end of the html. This works for most of the html loaded. However some complain that onload init() not found. This gets solved if i include the javascript in the html head. But than other htmls start behaving strangely. onload gets called before the page is fully loaded. i dont get the correct scroll width. Please suggest what could be worng. Whats the best way of including javascripts. Thanks
html is as follows
columizer id use css column-width which i've defined like this.
css style below
#columnizer
{
width:290px;
height:450px;
column-width:290px;
column-gap:10px;
word-wrap:break-word;
}
Javascript onload is defined like this.
function init()
{
docScrollWidth = document.getElementById('columnizer').scrollWidth;
document.getElementsByTagName('body')[0].style.width = docScrollWidth + "px";
window.external.notify(str);
}
Since the actual answer was in my comment, I'll add that to my answer:
My guess is that you're doing something like window.onload = init(); instead of window.onload = init; and the init function will have to be declared before you do that assignment. You assign function references without the parens. Using the parens causes it to get executed immediately.
You say you're using this code:
docScrollWidth = document.getElementsByTagName('body')[0].style.width
The main problem with this is that style.width ONLY reads a style attribute set directly on the body object. It doesn't get the width of the object as calculated by layout or CSS rules.
So, what you should use instead really depends upon what you're trying to do. The body width will nearly always be the same or more than the window width unless your content is entirely fixed width. So, that makes me wonder what you're trying to accomplish here? What you should use instead depends upon what you're really trying to do.
FYI, document.body is a direct reference to the body object so you don't need document.getElementsByTagName('body')[0].
First, let me define the problem. The window.onload event is used by programmers to kick-start their web applications. This could be something trivial like animating a menu or something complex like initialising a mail application. The problem is that the onload event fires after all page content has loaded (including images and other binary content). If your page includes lots of images then you may see a noticeable lag before the page becomes active. What we want is a way to determine when the DOM has fully loaded without waiting for all those pesky images to load also.
Mozilla provides an (undocumented) event tailor-made for this: DOMContentLoaded. The following code will do exactly what we want on Mozilla platforms:
// for Mozilla browsers
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
So what about Internet Explorer?
IE supports a very handy (but non-standard) attribute for the tag: defer. The presence of this attribute will instruct IE to defer the loading of a script until after the DOM has loaded. This only works for external scripts however. Another important thing to note is that this attribute cannot be set using script. That means you cannot create a script using DOM methods and set the defer attribute – it will be ignored.
Using the handy defer attribute we can create a mini-script that calls our onload handler:
<script defer src="ie_onload.js" type="text/javascript"></script>
The contents of this external script would be a single line of code to call our onload event handler:
init();
There is a small problem with this approach. Other browsers will ignore the defer attribute and load the script immediately. There are several ways round this. My preferred method is to use conditional comments to hide the deferred script from other browsers:
<!--[if IE]><script defer src="ie_onload.js"></script><![endif]-->
IE also supports conditional compilation. The following code is the JavaScript equivalent of the above HTML:
// for Internet Explorer
/*#cc_on #*/
/*#if (#_win32)
document.write("<script defer src=ie_onload.js><\/script>");
/*#end #*/
So far so good? We now need to support the remaining browsers. We have only one choice – the standard window.onload event:
// for other browsers
window.onload = init;
There is one remaining problem (who said this would be easy?). Because we are trapping the onload event for the remaining browsers we will be calling the init function twice for IE and Mozilla. To get around this we should flag the function so that it is executed only once. So our init method will look something like this:
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// do stuff
};
I’ve provided a sample page that demonstrates this technique.

HTML element no defined in Javascript

I have an html element:
<img alt="" src="../Images/ERROR.jpg" id="live1x4" height="288" style="width: 360px;
display: block;" /
If i refer to this control in javascript which is in the same html page:
live1x4.src = src;
Where src is the location of an image the script works.
If move that javascript to an external js file I get 'live1x4' is undefined.
This occurs ONLY in Internet Explorer.
Wjat can be causing this error?
You have to target your element, not simply refer to the ID:
document.getElementById("live1x4").src = ....
The reason is that the JavaScript code is executed before the img element has been parsed. Whether this happens depends on many things. There are different ways to ensure that it does not happen. A simple way is to wrap your code inside an even handler that is triggered after the document has been loaded:
window.onload = function() {
// your code here, here all elements are available, e.g.:
live1x4.src = src;
}
It is generally regarded as bad coding style to use id attribute values as if they were global variables (partly because they stop working ifsynonymous global variables are added), so document.getElementById("live1x4") is preferable to live1x4. However, this is a different topic.

Why doesn't $('body').html("") clear the javascript that calls it?

This is a piece of code that links to a javascript file that generates some fake tweets, along with some self made comments that attempt to explain to myself what is happening. I was wondering what the purpose of $body.html(''); was. It seems like it just clears the contents of the body, which is already empty except for the javascript that is present. Wouldn't this also clear the actual script that inside the body as well? i.e., why doesn't the whole script just vanish when we reach that line. I'm guessing that the function is executed in its entirety before the body is cleared? Just looking for a little illumination, I guess, on function execution.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script src="data_generator.js"></script>
</head>
<body>
<script>
$(document).ready(function(){ // calls function only after dom is loaded
var $body = $('body'); // selects html body tag, stores in $body
$body.html(''); // clears body?
var index = streams.home.length - 1; // sets index to length of streams array
while(index >= 0){
var tweet = streams.home[index]; // gets a tweet string
var $tweet = $('<div></div>'); // $tweet is a div element
$tweet.text('#' + tweet.user + ': ' + tweet.message); // add formatted tweet to div
$tweet.appendTo($body); // add tweet to body
index -= 1; // rinse, repeat
}
});
</script>
</body>
</html>
EDIT: To be clear, I didn't write the code, only the comments. I am just trying to break it down and understand each line.
When the Javascript is run the function context is stored in memory, and closed-over variables are stored in the context. They don't go away. Globals are attached to window. They don't go away either.
I think it is a better idea to append the script to the header (where all the other scripts reside) than to the body.
If you want to completely eliminate the script that is being called, you could use:
<script>
(function foo(){
var b=function moo(){
var c=document.getElementsByTagName('script');
alert(document.body.innerHTML);
c[0].parentElement.removeChild(c[0]);
alert(document.body.innerHTML);
}
var a=setTimeout(b,1000);
b=null;
})();
foo=null;
</script>
Keep in mind, that will COMPLETELY remove any functionality of the script and any reference to it in the DOM.
Basically, because the script has already loaded, you can't just remove it from the DOM.
Is there really any reason to get rid of it, now that it's already loaded...???

Categories

Resources