Window.onload and body.onload in IE - javascript

When I'm trying to run the following code in IE:-
<html>
<head>
<script language="javascript">
window.onload=function(){
alert("Window.onload is working");
}
</script>
</head>
<body onload="alert('body.onload is working')">
</body>
</html>
It seems that the body.onload overrides window.onload. I want both of them because I have a page and When I press a button, I get a second file and put it inside a div in the first page. So, I need to use window.onload in the first page and when I get the second one, I use body.onload of the second one.
I don't have this problem in FF,Opera,Chrome and Safari.
I hope my problem is clear. Thanks for any help.

Why not put a JavaScript command at the end of the content that's being subsequently loaded into the div? Hence, when the content is loaded the last line is a JavaScript triggering the call to your function. That's pretty much the simple way of making sure that: (1) content is loaded and (2) you create this function with full cross-browser efficiency.

If you see the following page regarding https://stackoverflow.com/questions/191157/window-onload-vs-body-onload, you'll find that they're the same thing. In other words, you're merely redefining what happens when the load event is fired.

If you "get [the] second file" using AJAX you should be able to use the response callback to perform any "onload" actions.
If you're using an iframe you should be able to bind to the onload event of the iframe's contentWindow.

Related

Alert box displaying before HTML

I am a total beginner in Javascript but not in OOP or HTML. I have started the Beginning Javascript book and have run into trouble with the second example. The following code should display p1 in my browser(Chrome) and then and alert box saying "first". However I do not understand why it is happening the other way around --- alert appears before p1.
<html>
<body>
<p>p1</p>
<script type="text/javascript">
alert("first");
</script>
</body>
</html>
EDIT: As an additional solution to problem of manipulating HTML elements with cross-browser compatability, I think jQuery would be an essential next step for web development after learning Javascript.
Please go through the link below to understand the load and execution order of the script.
load and execute order of scripts
The html is being rendered but as the alert is not triggered by any javascript event, it fires as soon as the dom is loaded. You do not have any bug and the behavior of your browser is ok.

Call a script where needed instead of inside body tag

I've got a script that uses <body onload="SlideShow()"> , but I don't want to call the script inside body tag. I also only want to call the script when needed. What is another method of calling the script where I can call the script where its going to be used.
So, lets say half way down the page I want to use the slideshow, I call it there.
Also, what if I have a slideshow in multiple places on the same page. Will calling it multiple times hurt anything or is there a method to prevent the script from being called more than once while still allowing the slideshow to continue. All settings are set inside the script, so all slideshows will run the same.
Via jquery:
$('#elemId').bind('event(s)', function(e){
SlideShow();
})
Smth like this, if i understood it correctly.
You want to call it half way down the page, then you can just write this,
<script type="text/javascript">
slideShow();
</script>
But I wouldn;t suggest writing in-line js.
Also, If you have an event on which you want to call the slideshow function, then just attach the function to that event.
Edit:
If you have multiple slideshows on the same page, normally they will all be separate instances and they all won't be initialized by slideshow()

Where exactly should I attach script in HTML?

I have read about several ways to embed Javascript in HTML document.
First, in head section:
<head>
...
<script src="abc.js"></script>
</head>
Second, in the end of document's body:
<body>
<!-- content -->
<script src="abc.js"></script>
</body>
First way is more esthetic, but second version assures that all the items in DOM are loaded. I use HTML5 (but probably it doesn't matter)
Which way is better and why?
if it is just a library of functions which aren't suppose to run when the page loads, you can safely put it in the head. Otherwise you need to wrap the code in abc.js with window.onload or $(document).ready(); and then embed it in the head
It depends on when you need the functionality in the script.
Before page load or else.
If it doesn't matter the second one in your example is better and more seciure since it allows the page content to load.
An error in the script may prevent for this to happen in before body case.
A lot depends on when you need script to execute if you need the page to be fully loaded or not. You can possibly put it in the head then execute a function with the onload event.

How to run scripts loaded dynamically with javascript

I was wondering if there is a way to execute script within a ajax dynamically loaded content.
I've searched the web and this forum also an find a lot of answers, like
[Running scripts in an ajax-loaded page fragment
[1]: Running scripts in an ajax-loaded page fragment [1]
But none of this seems to work fine for me.
I'm not experienced as the author of the quoted post, so maybe we can find a solution more simple and quite for everyone.
For now i've implemented a tricky turnaround that smell to much of an hard-coded solution that is:
//EXECUTE AJAX REQUEST LET'S SAY SUCCESSFULLY,
$ajax([..]) //THEN
.ajaxSuccess(function(){
// LOCATE ANY OBJECT PRE-MARKED WITH A SPECIFIC CLASS
$(".script_target").each(function()
{
//DO SOMETHING BASED ON A PRESET ATTRIBUTE OF THIS SPECIFIC ELEMENT
//EXAMPLE: <div class=".script_target" transition="drop_down">...</div>
//WILL FIRE A SCRIPT RELATED TO drop_down CASE.
});
});
I know this is an ugly solution but i didn't came up with nothing better than this.
Can you help to improve this method?
Maybe there's a way to let the browser fire script within the loaded page automatically?
PS. I'm not going to use the eval() method if it's not the last solution, cause both security leak and global slowdown, AND be aware that the script launched need to modify objects loaded in the same fragment of the script.
Thanks in advance.
If I understand you correctly :
you use "load" to retrieve html content from the server, and you add it to the page.
later, you do an ajax call, and on the return of the ajax call, you want to act on the markup you added earlier
but, depending on the markup retrieved, you want to do something different in the ajax callback
So another question : before you load the markup, do you know what logic will be behind it, or do you actually need to "read" the returned HTML to understand what it will be used for ?
Otherwise maybe something like this would work :
In the callback of the "$.load" function, use $.data() to attach more information to created dom object
In the ajax callback, you should be able to access the "added" markup (with a class like you did, or with an id if possible), and read to "data" to known which behavior you should have ?
Hopefully I got your problem right, it could help if you were able to create a jsfiddle or something, just to make sure we understand it.
Hoping this helps.
EDIT : After your comment, it might be related to the selector you use when calling $.load().
There is a "Script Execution" section in the $.load documentation : http://api.jquery.com/load/ , that explains that the scripts are not executed if you add a selector in the url, like this :
$('#b').load('article.html #target');
Could this be your issue ?
Also, if possible, you could try and change your site so that instead of having the js code of each "page" of the gallery inside the page, you put it inside a separate javascript file, that you load at runtime (for example with require js).
This way, "loading" a page would be something along the lines of :
$.load("url_of_a_page_markup.html", function () {
require(["url_of_the_javascript_module.js"], function (TheJsModuleForThePage) {
TheJsModuleForThePage.doSomething();
});
});
If you structure your JS modules in a consistent way, and you define a convention for the name of markup and js files, you can generalize things so that a "gallery" manager deals with all this code loading, and you'll end up with well isolated js modules for each page.
Hoping this helps.
If you want to run a script in a ajax loaded page fragment you can use try to use jQuery.load function.
Have you considered a module loader like require.js or Lab.js?
There are many other people asking similar questions:
does anyone knows good ajax script loader
Where are scripts loaded after an ajax call?
getting jQuery scripts and content through ajax dynamically
dynamic script loader in JS
Edit: I think I misread your question. Will try and come up with a better answer. Sorry!
Best of luck to you!
I came across this same issue when I dynamically loaded some HTML to use inside a JQuery UI dialog (a help function for my application).
$('#helpMessage')
.load('./help/' + helpFile, function () {...do stuff after loading});
To make things simple I wanted to combine the unique script related to the help page within the HTML fragment that I load. Using the examples on the JQuery UI page I created a dialog with a Jquery UI button element.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Button - Icons</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
(function() {
$('#myButton') // My button element
.button() // Initialize it as a JQuery UI button object
.click(function (){ // Hook up the button click event
$('#correct')[0].play(); // to play a sound in an <audio> tag
});
});
</script>
</head>
<body>
This is my help file, this is my code. This is for reading, this is for fun.
<button id="myButton">Button Text</button>
</body>
</html>
The dialog would load and the HTML displayed, but the embedded script did not execute.
I realized that one simple change would fix it. The script is embedded in an anonymous function (a best practice and part of the JQuery UI demo code). By immediately invoking the anonymous function the script executed when I loaded the HTML fragment into my main page.
This:
<script>
(function() {
...
});
</script>
Became:
<script>
(function() {
...
})(); // Immediately invoke
</script>
Niceness.

Load javascript after page load

I have an external javascript that contains something like:
document.writeln("<script type='text/javascript' src='...'></script>");
In the original html i have something link
<div id="banner">
<script type="text/javscript" src="<the external javascript above>"></script>
</div>
How can i load that delayed?
I've tried using window.setTimeout and append that javascript but its not working.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
Thank you.
You can call your injection code on window.onload.
window.onload = function() {
inject();
doSomethingElse();
};
window.onload will wait until all assets have finished downloading, such as images and scripts. After scripts are downloaded, you can inject your code to page.
Maybe a better way to do it would be to add a delay to the script.
Also, if you use something other than 'document.writeln' for example:
$('#banner').append(...);
you can better direct where it goes.
There is an open source javascript library for doing this kind of thing: http://labjs.com/
I have used it in the past and it worked very well.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
That is not entirely true. Especially if the div is empty you could simply use: document.getElementById('banner').innerHTML = "<h1>HTML-Output here.</h1>"
Bukko's answer would work as well if you are using jQuery. My answer is pure Javascript. With this newfound freedom you should be able to simply put the loading of your script at the bottom of the page or use a custom body.onload() function
Edit: or simply follow Samet's suggestions in conjunction with the .innerHTML. Hope this helps.

Categories