I am trying to use jQuery's .load function to dynamically load content into my webpage. This seem so simple, but I cannot make it work. To try and figure it out, I made a test page with just basic structure, but the external content still won't load:
jquery.html
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$('#foo').load('test.html');
</script>
<div id="foo"></div>
</body>
</html>
test.html
<p>Text text</p>
I'm sure I have made a tiny error, but I can't find it anywhere!
You need to encapsulate your script in the $(document).ready() otherwise #foo won't exist when the script is executed:
<script>
$(document).ready(function(){
$('#foo').load('test.html');
});
</script>
You need to wait for the document to be ready before you can access the DOM. Just add a $(document).ready() around your original code:
<html>
<head>
<title>JQuery Test</title>
<script src="jquery1.5.min.js"></script>
</head>
<body>
<script>
$(document).ready( function() {
$('#foo').load('test.html');
});
</script>
<div id="foo"></div>
</body>
</html>
or if you want a shorter code:
$(function() {
$('#foo').load('test.html');
});
Informally, what's happening is that, as your browser reads the code you wrote, it's drawing its contents as it goes along. When it reaches your <script> tag, it executes it. But when $("#foo") gets executed, the browser's still processing the <script> and hasn't reached the part of the code where you told it there's a div called foo, so the browser doesn't know it exists, and jquery will just find nothing.
Of course, the idea that the browser will just sequentially read your code and render it as it goes is naive at best, so while it might seem that just moving the <script> tag to the bottom of the code would work, you're not actually guaranteed it will work. Instead, the browser will notify you when it's done drawing the page by firing a load (and possibly a DOMContentLoaded) event. So all code that depends on the whole html being drawn should be executed in an event handler bound to those events.
jQuery makes waiting for the page to be loaded easy, just use something like this:
$.ready(function() {
doStuff();
});
Related
I have a page with a javascript file at the end. the file is placed at the end so that I get access to all the dom elements.
let us say the markup looks like this
<html>
<head></head>
<body>
//lot of markup here
<script src="my-js.js"></script>
<body>
the sample markup is just to show the location of my js file.
the first like in the js file (my-js.js) is
document.body.style.visibility = 'hidden';
After the code runs I set the visibility back to hidden
From what I have understood(from a lot of articles related to this including in stackoverflow ones) is that the browser reaches the js, then executes it, and then continues with render and then paints.
If that was true, my code as described should work fine.
However, what is happening now is that, the page is shown (for less than 500ms) as it is before the code executed, then quickly hidden and then shown again after the code executed.
in short, what I want is:
page is hidden > code executes > page is shown
instead what I get is
page is shown > page is hidden > code executes > page is shown
My question is why is the page shown for that split second? what am I doing wrong here?
PS: Please note that I cannot change the location of the js nor add another. So, do not post any solution that suggest the same.
More importantly, I want to know why my code is wrong.
You might be interested in using the defer method.
defer means “wait for the parser to finish to execute this”. It’s roughly equivalent to binding your script to the DOMContentLoaded event, or using jQuery.ready. When the code does run, everything in the DOM will be available for you to use. Unlike async, defer’d code will run in the order it appears in the HTML of the page, it is just deferred until after the HTML is fully parsed.
For example:
<script src="my-js.js" defer></script>
See more here
Put the script tag right at the start of the body so it will be evaluated almost exactly as the body is rendered.
<html>
<head></head>
<body>
<script>
document.body.style.visibility = 'hidden';
</script>
<p>Sample text</p>
</body>
</html>
You can also add a style tag to set the body's visibility to hidden.
body{
visibility: hidden;
}
<html>
<head></head>
<body>
<p>Sample text</p>
</body>
</html>
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>
Nothing in jQuery appears to be working in Chrome for me. My version is 18.0.1025.151 m. The javascript is in the file test.js:
$('#paragraph').click(function() {
$('#paragraph').hide();
});
And the html is this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Example</title>
<script src="jquery-1.7.1.min.js"></script>
<script src="test.js"></script>
</head>
<body>
<p id="paragraph">This is my paragragh 401!</p>
</body>
</html>
I have triple-checked that the jQuery file is where it's supposed to be. Essentially, the code is supposed to make the paragraph disappear when clicked on. Seems simple enough and syntactically correct. I chose such a simple code because while regular javascript statements and code work fine (such as alert() and whatnot), absolutely nothing in jQuery has worked so far at all.
Here's the strange part though. When using the console in Chrome's developer tools, if I input the exact same jQuery stuff and hit enter, it actually works and functions how it's supposed to.
Does this have anything to do with Chrome's security structure or something?
Edit: Also, I should note that I have not yet uploaded these files on my server yet. This is on localhost (I'm using xammp for what it's worth), so perhaps that may help shed some light on the issue.
Wrap the code in a document ready, or put test.js before the end body tag.
It's executing before the DOM is ready. It should look like this:
$(function(){
$('#paragraph').click(function() {
$('#paragraph').hide();
});
});
To address the comment below:
http://api.jquery.com/ready/
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
// Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
// Handler for .ready() called.
});
You have to wrap it in document ready. That's probably your problem. Also you can use $(this) or cache the selector.
$(function () {
$('#paragraph').click(function () {
$(this).hide();
});
});
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.
i use that tag to alert me when a tag has been shows up
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
<iframe></iframe>
</body>
</html>
strange , since this code working :
<html>
<head>
</head>
<body>
<iframe></iframe>
<script type="text/javascript">
document.getElementsByTagName('iframe')[0].onload = function() {
alert('loaded');
}
</script>
</body>
</html>
why the Js need to under the tag to work?
what's the problem here?
Because the code in a script tag is executed immediately. And in the first example the iframe doesn't exist at that time. But what you can do is to wrap you code into an onload (for the main page) event. E.g.:
window.onload = function() {
//your code
}
Then it doesn't matter where the code is placed.
Iframe tag does not exist at the moment you are trying to access it.
You may check that by simply alerting array length, like
alert(document.getElementsByTagName('iframe'));
Have you thought about executing your javascript after the page is loaded? You may use some frameworks like jQuery to facilitate crossbrowser issues. Or just put all your javascript code to the very bottom of body.