Ok, I made 2 posts about this but somehow I can't get it into my little mind.
So I concluded that if we have something like this:
<script type="text/javascript" src="somefile.js"></script>
<script type="text/javascript">
func1();
</script>
and func1() is defined in somefile.js, it is guaranteed to run when browser reaches that inline .
However, what if I have a big page (not taking into account images etc, just html) that takes a few seconds to load and for DOM to become ready (as I understand the DOM becomes ready when the whole html code has been loaded and parsed) and I want some code to be executed and work on parts of the page that have been loaded while the rest of the big page is still loading?
For example something like:
<div id="div1">Some div where content will be inserted by the inline javascript below</div>
<script type="text/javascript"> notifyPartLoaded("div1"); </script>
^^ Does something like this exist?
I'm not certain what your question is, but a simple way to ensure DOM ready is to place your JavaScript at the bottom of the HTML, just in side the closing </body> tag.
<!doctype html>
<html>
<head>
<title>some title</title>
<!-- this script could go toward the bottom too, but it must be before -->
<!-- your script if your script relies on it -->
<script type="text/javascript" src="somefile.js"></script>
</head>
<body>
<div id="div1">Some div where content will be inserted by the inline javascript below</div>
<!-- your HTML -->
<!-- your HTML -->
<!-- your HTML -->
<!-- Place your script last -->
<!-- ...though it would be better to have it in a separate file -->
<script type="text/javascript"> notifyPartLoaded("div1"); </script>
</body>
</html>
Because your code is after all the other elements, they will exist for manipulation when your code finally loads and runs.
Related
Since I started using a html-templatefile for my navbar elements I haven't got one of my scripts to execute(I can execute it via the console). I have experimented with on-load-functions but even that didn't seem to work. My problem is that I understand to little of the execution order and if I'm somehow blocking my script. I don't get any error messages either and when the html-template isn't used (ie - the navbar structure is included with everything else in the same html-file) the page loads as it should. So something there is messing it up. And I can call it from the console as well.
(I have tried a variety of ways but nothing have really worked, other than including the template in the document and that I would like to avoid. This setup is one of many). I hope someone can see the errors I do on the spot. I have cut out som css aswell, for readability.
Edit: Threw js out the window, since ASP was found available. Solved it in about half an hour using asp.
Just place your DOM elements inside body tag. Always render script at the end of the body, and append async javascript files at document ready (or at least this is my view of things).
<html>
<head>
<link href="Bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body id="bodyCanvas">
<div class="masthead">
<div class="container">
</div>
</div>
<div class="container Override" id ="pageContainerId" >
</div>
<script>
<script src="http://code.jquery.com/jquery.js"></script> // create a local copy of jquery and other async javascript files you can load at $(document).ready(function(){ //here append async scripts like google maps });
<script type="text/javascript" src="d3.min.js"></script>
<script src="Bootstrap/js/bootstrap.min.js"></script>
<script type='text/javascript'>
$(function(){
$("#pageContainerId").load("navbarTemplate.html");
});
</script>
Here goes code....
</script>
</body>
</html>
The code you are trying to reference in the $("#pageContainerId").load("navbarTemplate.html"); is outside the body tag and most browsers will cut this out.
Try the following:
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="d3.min.js"></script>
<script src="Bootstrap/js/bootstrap.min.js"></script>
<script type='text/javascript'>
$(function(){
$("#pageContainerId").load("navbarTemplate.html");
});
</script>
</head>
<body id="bodyCanvas">
<div class="masthead">
<div class="container">
</div>
</div>
<div class="container Override" id ="pageContainerId" >
</div>
<script>
Here goes code....
</script>
</body>
</html>
Also as the script is at the top the DOM may not be loaded at the time try the following:
$(document).ready(function(){
$("#pageContainerId").load("navbarTemplate.html");
});
DOM ELEMENT SHOULD INSIDE BODY TAG
<body id="bodyCanvas">
<div class="masthead">
<div class="container">
</div>
</div>
<div class="container Override" id ="pageContainerId" >
</div>
</body>
Ok, I couldn't get it to work the way I wanted but it turned out we had asp enabled on our server so when I switched to that I got it to work beautiful in about half an hour.
And it's a better way I suspect, in terms of best practice.
Thanks for the responses.
I'm new to HTML, JavaScipt and everything related to programming, and I'm trying to create a simple page.
Now, I'm stuck with the following problem: I want to change the date of my main.html file, but the main.js is not working. I've already change the <script> position to inside the <body>, after the </span> and even after the </body>, without success. If the content of the main.js is within the HTML it works fine, but as a external file it doesn't.
Here is my main.html:
<!DOCTYPE html>
<html>
<head>
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="main.js"></script>
<title>Page 1</title>
</head>
<body>
<p>WRF<br>
<span id="data">18/09/1987</span></p>
</body>
</html>
My main.js is just:
document.getElementById("data").innerHTML = "JUBA";
I've looked through the internet and through this forum, but all answers that I've found did not worked.
The files are on the same directory and the main.css works fine.
Thank you in advance.
At time you call main.js element #data was not created in DOM tree. You can fix this by putting the link to your Javascript file right before closing the body like this:
<script type="text/javascript" src="main.js"></script>
</body>
Document Object Model (DOM) is not "READY".
Try use onload event, inside main.js:
window.onload = function() {
document.getElementById("data").innerHTML = "JUBA";
};
If needs more "fast" than onload, use jquery with $(document).ready:
html:
<link href="main.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="main.js"></script>
main.js:
$(document).ready(function() {
$("#data").html("JUBA");
});
window.onload vs $(document).ready()
Answer by #Guffa:
The ready event occurs after the HTML document has been loaded, while the onload event occurs later, when all content (e.g. images) also has been loaded.
The onload event is a standard event in the DOM, while the ready event is specific to jQuery. The purpose of the ready event is that it should occur as early as possible after the document has loaded, so that code that adds functionality to the elements in the page doesn't have to wait for all content to load.
The element is not yet accessible when you run the script.
Either you can put the script at the end of the page or delay the execution.
You could put the JavaScript in the <body> tag after the rest of the page. When the browser loads it, the <span> will already be there to be edited.
As per your code the script will be called first then page will be loaded, therefore when the script is running there will not be any element having id data because yet page have to be loaded. There are many ways to achieve what you need.
1. Add a script tag before or after end of body like
or
<script type="text/javascript" src="main.js"></script>
</body>
Write .js file above before body i.e. in head tag and write the whole javascript code in onload method.
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
window.onload=function(){
document.getElementById("data").innerHTML = "JUBA";
};
<p>WRF<br>
<span id="data">18/09/1987</span></p>
When i keep my javascript/jquery external, my code doesn't work. but when i combine them in my html file everything is fine.
any suggestions as to why this is?
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="program.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
with external javascript
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
VERSUS
<!DOCTYPE html>
<html>
<head>
<script type ="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
</script>
</body>
</html>
I guess you execute the click event before the DOM finishes loading. Wrap your code inside the dom ready event and it should work, Assuming your path to the external javascript file is correct.
$(function(){
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
});
Always use firebug (console) to see what is wrong with the script, if you run into any script errors.
Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...}); or moving your external javascript files to the bottom.
Wrap your js code in external file in
$(document).ready(function(){
//your code goes here
});
Right now you are including external js file in header and it is executed. At this point there is no elements so $('#clickme') and $("p") are empty set. In the second example you run this code after rendering html with that elements.
The reason that there is a difference, is that in the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit further...
Whilst a lot of people have mentioned using jQuery's document ready handler, I would like to point out that a workable solution is simply to move your script tags to the bottom of the page.
Not only will this solve your problem in itself, but it will also improve page load times because of how browsers treat scripts. When the browser encounters a script it stops everything else it is doing (known as a "blocking" operation), and parses and executes the script. This causes the page to just appear to stall from a user's perspective, meaning a bad user experience. Thus, because the scripts are parsed and executed only as they are encountered, by moving your scripts to the bottom you allow the browser to fully render the page so that the JavaScript does not block rendering.
Though rather than just moving scripts to the bottom of the page, I'd also follow what the others recommended and wrap the whole code in the document ready handler just to be extra safe that your code will always be executed at the correct time.
Also, in the debate of inline or external, external scripts are generally preferred as they are easier to maintain and the browser can cache them independently of the page (providing the correct HTTP headers are present).
To sum up here's some example code:
<html>
<head></head>
<body>
<!-- all your markup here -->
<!-- script at bottom, markup already rendered by this point -->
<script type="text/javascript" src="jquery.js"></script>
<!-- inline or external, still wrap in document ready handler -->
<!-- though external is better because the browser can cache it independently of the page -->
<script type="text/javascript">
//wrap in document ready to be extra safe
$(function() { /*code here*/ });
</script>
</html>
I am not clear why its not working the javascript code when I add it to the header section as follows.
We can place a javascript code within the body as follows
<html>
<head>
<title> Simple Test </title>
</head>
<body>
<div id="mydiv"> This is the div content </div>
<script type="text/javascript" >
document.getElementById("mydiv").innerHTML=Date();
</script>
</body>
</html>
But when I place the same JavaScript code in the header section it doesn't work.
<html>
<head>
<title> Simple Test </title>
<script type="text/javascript" >
document.getElementById("mydiv").innerHTML=Date();
</script>
</head>
Can Someone please explain the issue. I know I can Write a JavaScript function in header and call it in an event. But can't we Use in this way. If Can't why.
<html>
<head>
<title> Simple Test </title>
<script type="text/javascript" >
window.onload= function (){document.getElementById("mydiv").innerHTML=Date();}
</script>
</head>
I think above code will help you to solve your problem. You can try this one.
because when the page is loaded, by the time the browser gets to that <script> element, the #mydiv element has not yet been created.
either use an "onload" event, or put your scripts at the bottom of the page.
It's because the page is being rendered in the order it's read. Therefore when the script in the header is evaluated the rest of the page hasn't been rendered yet (ie the myDiv element hasn't been created).
When you create an event handler in the head that works fine - the handler is set up before the rest of the page is loaded but the event can't happen until the element exists.
When you put it in the <head>, it runs before the <body> exists.
this is because of the page rendering order.you can access elements before it has been created. if you can, try to put all JavaScript code end of the page(before closing body tag). it will save your page load time. if you cannot put it in the bottom, put the code inside onload event.
On my site a number of operations can take a long time to complete.
When I know a page will take a while to load, I would like to display a progress indicator while the page is loading.
Ideally I would like to say something along the lines of:
$("#dialog").show("progress.php");
and have that overlay on top of the page that is being loaded (disappearing after the operation is completed).
Coding the progress bar and displaying progress is not an issue, the issue is getting a progress indicator to pop up WHILE the page is being loaded. I have been trying to use JQuery's dialogs for this but they only appear after the page is already loaded.
This has to be a common problem but I am not familiar enough with JavaScript to know the best way to do this.
Here's simple example to illustrate the problem. The code below fails to display the dialog box before the 20 second pause is up. I have tried in Chrome and Firefox.
In fact I don't even see the "Please Wait..." text.
Here's the code I am using:
<html>
<head>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.dialog.js"></script>
</head>
<body>
<div id="please-wait">My Dialog</div>
<script type="text/javascript">
$("#please-wait").dialog();
</script>
<?php
flush();
echo "Waiting...";
sleep(20);
?>
</body>
</html>
You'll need to run that piece of code immediately after your <body> tag, something like:
<html>
<head>
</head>
<body>
<div id="please-wait"></div>
<script type="text/javascript">
// Use your favourite dialog plugin here.
$("#please-wait").dialog();
</script>
....
</body>
</html>
Note I omitted the traditional $(function (){}) because you need this to be loaded as soon as the page is shown, not after the whole DOM is loaded.
I've done this before and works great, even if the page has not finished loading yet.
EDIT: you'll have to be certain the jQuery dialog plugin you're using is loading before your entire DOM loads. Usually this is not the case, you it won't work. In that case, you'll need to use a g'old plain JavaScript solution, such as Lightbox 1 or Lightbox 2.