I've picked up an existing project from another developer and ive noticed in the code that they are executing js code within three different event handlers...
function pageLoad() {
//execute code
}
$(document).ready(function() {
//execute code
});
$(function() {
//execute code
});
My question is - arent they all exactly the same? Or at least the last two? I understand that pageLoad is called by the .NET framework so it's not dependent on the jQuery library having loaded like the second two are - that's my understanding anyway - is that about correct?
$(document).ready()
Ideal for one time initialization.
Optimization black magic; may run slightly earlier than pageLoad().
Does not re-attach functionality to elements affected by partial postbacks.
pageLoad()
Unsuitable for one time initialization if used with UpdatePanels.
Slightly less optimized in some browsers, but consistent.
Perfect for re-attaching functionality to elements within UpdatePanels.
pageLoad and the jQuery ready handler are both methods of accomplishing similar things.
The second two examples are identical.
http://encosia.com/document-ready-and-pageload-are-not-the-same/
The last one is just a shorthand notation of the one above it. http://www.jquery4u.com/dom-modification/types-document-ready/
$(document).ready(function() {
`enter code here`
//execute code
});
$(function() {
`enter code here`
});
Both functions perform task in the same way, executes code inside them once the document is ready.
function pageLoad() {
`enter code here`
}
This executes after every post back, generally used with update panels controls as the above two functions does not execute every time or every post back.
$(document).ready() will not fire for the partial postbacks (happened from AJAX). In that case, you should use MS AJAX pageLoad function when you need to execute something when the page loads either from the full postback or partial.
The article given in the Encosia site is a good read.
In this site you will find the difference :)
Document.ready Vs pageLoad
Related
So I have this block of code:
$(document).ready(function() {
planSelectionForm.init($("form#new_account"));
});
And when I link to this page it works as expected. But when I refresh from the browser it doesn't get triggered. This seems like a common problem. Just for the record I'm using turbolinks. Any help on why this is happening would be great!
The only solution I could find after getting this problem was wrapping my script with:
document.addEventListener("turbolinks:load", function() {
planSelectionForm.init($("form#new_account"));
});
Wrap your .onready() functions into a function called initialize. The point, is to seperate the event-driven function calls such that the event driven function call calls a global function.
In there, add to your body or another element that supports onload.
$(document).ready(function() {
initialize();
});
function initialize()
{
}
<body onload="initialize(); return;"> </body>
Also, for Caleb, in my experiance, I believe jQuery ready events only get executed on either a fresh load, or a ctrl+f5 cache reload.
First time using jQuery. I'm using it to load the content of an external element onto my page. It loads fine, but I'm finding that the normal traversal methods don't work on the loaded elements. For instance, what I have is:
<div id="area"></div>
<script type="text/javascript">
$("#area").load("externalPage.html #externalElement > *");
$("#area").find("ul").first().css("display","none");
</script>
The second line of the script appears to do nothing. Does this have something to do with the order in which operations are completed?
I'm loading this into a custom HTML module on the Blackboard LMS, which can sometimes behave strangely if scripting gets too complicated, so this could very well be another one of those times. Thank you for helping me figure it out!
The call to load() is asynchronous. This means that your find() is being run before the request completes and the elements are created in the DOM.
To workaround this you can put your logic in the callback parameter of load(). This means that it will not be called until the request completes and the DOM is in the state you expect. Try this:
$("#area").load("externalPage.html #externalElement > *", function() {
$("#area").find("ul").first().css("display","none");
});
.load() has a callback for when it's done. You can do what you want to the new markup in there.
$("#area").load('foo.html', function () {
/* Now you have access to foo.html's markup */
});
You need to put that second line in the callback to .load():
$("#area").load("externalPage.html #externalElement > *", function() {
$("#area").find("ul").first().css("display","none");
});
Things like $.get() and $.fn.load() are convenience functions built on the basic jQuery $.ajax() system. The process of loading content is inherently asynchronous.
How do I make sure the alert comes after the loading of the external HTML?
function changeContent(){
$('#contentmain').load("contentmain.html", function(){
alert("something");
}
)}
I've been playing around with $(document).ready, but no luck so far.
Many thanks!
Update:
The result of this code is that it depends (on what, I don't know): sometimes the alert comes first, sometimes it comes second...
Your code is right.
From the jquery documentation:
Callback Function
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
are you loading iFrames?
try the .load() function.
$('#iframeID').load(function(){
// I am totally loaded and lets begin the hunt now.
});
Alternatively, If you are loading content via ajax, you can use .ajaxComplete
$(document).ajaxComplete(function(){
// ajax call has completed and lets begin the hunt now.
});
I have a very bare HTML page that loads two JS files. One of these JS files then goes and loads a varying amount of content into the page.
I'm trying to get the equivalent of window.onload for this extra content. Obviously, window.onload actually fires very quickly, when the page is done loading the two JS files.
Any ideas? I know I can go and attach onload events to every image/script/etc on the page, but would rather not...
EDIT. If the callback won't help .load should do the job. I've added it to the example.
In this case you need a call back. Are you using a JavaScript library? if so what library?
In your existing code, after you append to the document you need to call a function that can execute the next bit of code.
something like this.
//FILE 1
$(function () {
$('body').append(someHTMLOrDOMNodes);
//I don't know what your second script does, but you should name this callback something relevant.
$('#idOfNewContent').load(function() {
callback();
});
});
//FILE 2
function callback() {
//next bit of code.
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have a main page with 2 links that load external files via .load(). The first file has a simple JavaScript rollover, which works when the content is loaded. The second file has a jQuery plug-in that does not work when loaded via .load() - but works fine when the data file is viewed by itself.
Main file: http://gator1105.hostgator.com/~carc/test-load.html
Second data file that works by itself, but not from .load(): (same URL as above, but the file is test-load-two.html - StackOverflow will allow me to create only 1 hyperlink)
Rather than paste my source code here, you can just view it from the pages themselves.
How can I get the second file with the slideshow to work when loaded with .load()?
I acutally did something similar with a site I'm working on. What you'll want to do is make a callback function for each page for the $.load() call on the main page.
See the following code from the jquery.load() documenation:
$('#result').load('ajax/test.html', function() {
alert('Load was performed.');
});
In your particular case, you'd want something like this on the main test-load.html page.
$(document).ready(
function(){
$('li').click(function(){
var showThisContent = this.id;
$('#content').load('test-load-'+showThisContent+'.html', function(){
if (showThisContent == "one"){
//Do logic for test-load-one.html
//Pre-load your images here.
//You may have to assign a class to your anchor tag
//and do something like:
$('a.assignedClass').mouseover(function(){});
$('a.assignedClass').mouseout(function(){});
} //end if
if (showThisContent =="two"){
//Do logic for test-load-two.html here
$('.slideshow').cycle({
fx: 'fade',
speed: 500,
timeout: 0,
next: '.nextSSimg',
prev: '.prevSSimg',
pager: '#SSnav',
cleartype: true,
cleartypeNoBg: true
}); //end .cycle()
} //end if
); //end .load(location, callback function())
}); //end $('li).click()
}); //end $(document).ready()
Now, obviously I didn't convert all your code, but what's happening here is that once document.ready is complete, the callback function will run, and since the elements like '.slideshow' are now loaded into the DOM, you're callback code will bind to them appropriately.
You could switch this code around in several ways to have the same result (i.e., wrap 2 $.load()s into conditions rather than doing the conditional logic in the .load callback, and/or put a callbackOne() and callbackTwo() function above document.ready and then call them appropriately) but that's your preference. You should be able to do what you want to using the callback function argument of the $.load().
Ignore this answer
Your second file does its initialization in a "document.ready" block. That's not going to be run when your content loads via AJAX. Try taking the code in the second page that's inside "document.ready" out of that, so that it's just a bare script block.
[edit] Oh I see - not only is the script inside a "document.ready" block (well, it's not anymore), but that second page is a complete HTML document. You can't really load a complete HTML document into the middle of another document; it doesn't make sense, and jQuery is only going to grab what's in the body. Thus, try moving your script tag into the body and see what happens. (You still don't want "document.ready", I don't think.)
[edit again] actually I take that back - I don't think jQuery strips anything out; I just bet the browser gets confused.
[edit yet again] ok, ok I see that you've changed it again - let me take a really close look.
OK here's a better answer: for reasons I don't understand, when you load a fragment (or a whole page; whatever) with jQuery using the special "selector" trick to pluck out just a portion of the document:
var showThisContent = this.id;
$('#content').load('test-load-' + showThisContent + '.html #content-area');
the jQuery library strips out the scripts completely from the content, and doesn't ever run them. Why? I don't know.
I know that you probably don't trust me anymore, but here's what I did with your source code: I took that second file (test-load-two) and stripped out the head and stuff; basically I made it a fragment containing only the "content-area". (I also got rid of the script tag that loads jquery, as you don't really need that since the outer page already has it.) Then I changed the main page (test-load) so that when it calls "load" it just passes in the URL without that '#content-area' selector. That works.
[edit] I just posted a question to the jQuery forum: http://forum.jquery.com/topic/the-load-function-and-script-blocks
Don't go for $.load. Try $.get instead, which might seem less comfortable, but it worked for me in a different case. Sample code as following.
$(li).click(function() {
// your code for finding the id
$.get('test-load-' + id + '.html', function(responseHtml){
$('div#content-area').empty().append($(responseHtml)); // remove all elements from #content-area
// $('...').html(responseHtml) will not work
});
});
I hope this solves your problem.