JQuery load function page loading issue - javascript

I have a main.html in which I am trying to load another HTML.
The code in main.html is like this:
<script type="text/javascript">
$(window).load(function(){
$("#divid").load("sample.html");
});
</script>
Inside the sample.html, I have another JavaScript which doesn't work as expected.
<!-- inside sample.html -->
<script type="text/javascript">
... Some JavaScript here ...
</script>
I do not even get the width of an element correctly. Surprisingly, if I put a breakpoint in the JavaScript or put an alert, all seem to work well. This made me guess that page might not be loaded when script runs and by putting alert or breakpoint gives it a bit more time ? I did some searching on web and think that the loading is not in sync which means that the script inside the sample.html page is executing before the page could load. This is just my guess.
I have tried adding JQuery functions ready and load inside the sample.html as well but nothing changes.
Any idea what could be wrong here ?

Use the callback...
this is an example from the doku
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
http://api.jquery.com/load/
and also use jQuery's
$( document ).ready(function() {
console.log( "ready!" );
});
Document ready fires the callback, when the dom is ready. And load fires the callback when the file is loaded.
//EDIT
Please use document ready... here are more details... and also do not load files directly from the file system
$(document).ready(function(){
// You will enter here, wenn the DOM is loaded and ready to use
//When everything is ready to roll you want to load your html file
$("#divid").load("sample.html",function(){
// You will enter this method when sample.html is loaded
// Make sure there is also a div with the id=divid
// to get details on why this is not loading you can also use the
// function signature
// $("#divid").load("sample.html",function(responseText, textStatus, jqXHR){});
// You should also be aware of loading a file from file system can cause to ajax
// errors if it is not served by an http server. Because you can't access local
// files from within JavaScript (security thing)
});
}

Related

Moving HTML with jQuery makes chart.js charts dissapear, no errors, unknown reason How can I redraw it?

I have a page with several Chart.js charts. The page has two views: TABULATED (bootstrap) and SEQUENTIAL. Then, when the page loads, organizes the charts into the tabulated view automatically (each tab is for each chart). The sequential html structure is:
<div class="chartsCotainter">
<div class="chart1">
<!-- here is the chart 1 ... -->
</div>
...
</div>
The problem is when the charts is finally organized disappears strangely. The solution I found to solve the problem is to organize the charts in the tabs after 5 seconds using setTimeout
function refreshView()
{
console.log("Refreshing...");
organizeChartsInTabs();
}
setTimeout( refreshView, 5000 );
I don't want to use setTimeout, I believe that is necessary to redraw all the charts after organize it, I don't know how. I tryed .update() but no success.
As there is no complete source you provided. The problem I understood is with the page load. You are executing some JavaScript functions before all related things loaded.
You should try jquery document ready function
// A $( document ).ready() block.
$( document ).ready(function() {
console.log( "ready!" );
});
Put your call inside the ready function.
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute. Code included
inside $( window ).on( "load", function() { ... }) will run once the
entire page (images or iframes), not just the DOM, is ready.
So your code will be something
// A $( document ).ready() block.
$( document ).ready(function() {
organizeChartsInTabs();
});

Using jQuery Load Function before DOM Ready

I have a page that renders HTML blocks from another page on the same domain using IDs. My current code:
<div id=”testdiv”></div>
<script>
jQuery(document).ready(function(){
jQuery('#testdiv').load('/references/embed1.html #testdiv2');
});
</script>
While this loads the content correctly, there is a visible lag between the page loading and the jQuery content loading; depending on the DIV contents it sometimes a full second to display then it just pops into place. This is obviously due to the page not attempting to retrieve the HTML content until DOM Ready so I removed the ready function but the Load function doesn’t run. If I use an iFrame instead it appears to load as the browser executes the code but I lose the ability to only include specific DIV IDs and it’s difficult to make it responsive. Looked at $.ajax but apparently Load uses .ajax so it doesn’t look like there will be a difference.
Simply put – how do I load specific DIV ids from another page without waiting for DOM Ready whether jQuery, JavaScript, iFrames or other method? Second question
Thanks
document readywill be triggered until the whole page were loaded, just remove it and .load() will be invoked after #testdiv had finish render on DOM.
here's the example
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div id="testdiv"></div>
<div id="error"></div>
<script>
$( "#testdiv" ).load( "/references/embed1.html #testdiv2", function( response, status, xhr ) {
alert("Triggered");
if ( status == "error" ) {
var msg = "Err trying to load ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
https://jsfiddle.net/Angel_xMu/rer3yuny/1/
Ajax is not instant, and nothing you do will change that. Therefore, there will always be some form of delay. You can reduce the delay by removing the need for $(document).ready(), however I suspect it still won't be enough to have it do what you were hoping for.
$.get('page.html', function (result) {
// note, you may need to use `.filter` rather than `.find` depending on the structure of `result`
$('#target').html($($.parseHTML(result)).find('#target2'));
});
or leave your code as is minus $(document).ready and move it to after the target div just like in your example.
The only way to completely remove the delay would be to remove the need for using $.ajax by inserting the html directly into the page server-side.

Catching an element "load" event for append()-ed elements using jQuery?

So, I have a div (id="content") where I'm loading various other HTML I get from AJAX requests. I want to be able to tell when they have loaded successfully, but the load event does not seem to work with append().
I have this simplified example to illustrate the situation (in the real case, the listeners for the 'load' event are registered in different files which get loaded in the section of the script)
<html>
<head>
<script
type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js">
</script>
</head>
<body>
<div id="content"><div>
<script type="text/javascript">
$(document).ready( function () {
// this does not seem to work
$("#myDiv").on('load', function () {
console.log("myDiv loaded");
});
// neither does this
$("#content").on('load', "#myDiv", function () {
console.log("myDiv loaded by delegation");
});
// the content to append will come from the network
$("#content").append($("<div id='myDiv'>myDiv</div>"));
});
</script>
</body>
</html>
Of course, in the real case things are more complex (the loaded data can be anything) so these are not valid options:
having a function called after the div has loaded
having a function embedded in the loaded code (the code is generated from template files)
If you get the data from Ajax requests you should actually use the Ajax done() function. Since the call is async, you wont be able to listen to the changes in the div. Another solution would be to add a body delegate on the div and make it listen to the change event.
$("body").delegate("mydividentifier", "change", function(f){});
$.ajax().done(function(f){});

Why do I need to add $(document).ready to a self-executing function?

I'm just messing with some javascript and I came across something that puzzled me a little.
I've added a link to a script file into the header of a document, just after the link to jQuery.
If I place in the test file:
(function($){
$("#thing").mouseover(function(){alert("woo");});
})(jQuery);
The mouseover event does not trigger the function.
However, if I add
(function($){
$(document).ready(function(){
$("#thing").mouseover(function(){alert("woo");});
});
})(jQuery);
The event does work.
Is it simply that without $(document).ready the DOM hasn't finished loading at the point when my self-executing function runs, so there is no #thing yet to attach the function to or is there another explanation?
I've added a link to a script file into the header of a document
This is the point.
Usually people put script files in the footer of document to optimize the process of loading the page, therefore it would not need to wait for the document to be ready to execute something based on the DOM already loaded (if you are in the footer, you have already loaded the rest - unless you have some content loading async).
Try putting your script file in the footer, and you will not need the $(document).ready.
Summary: In your case you need it, because when the script starts executing you have not started yet looking for the DOM, and the element cannot be found in that time.
It's because document ready waits until the document has fully loaded before executing.
Anything that binds to DOM elements must be done when the document is fully loaded otherwise those event handler bindings will be trying to bind to DOM elements which don't yet exist.
So yes, you answered your own question.
$( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute
It waits for the entire HTML excepts the Images.
some times you noticed that you recived an error “$ is not defined.” then in that case
you can use $( document ).ready()
You can just move the $ to make it work
$(function(){
$("#thing").mouseover(function(){alert("woo");});
});
Demo
Explanation $(function(){}); is equivalent to $(document).ready(function(){}); in jQuery
The document ready function waits for the page to load and
then executes whatever is in there. This prevents immature
actions before the page loads.
As a thumb rule, remember this,
$(document).ready(function(){
//jQuery code goes here
});
Apparently this works for me
<div id="body">
<section class="featured">
<div class="content-wrapper">
...
</div>
</section>
</div>
#section scripts{
<script type="text/javascript">
(function ($) {
$(".featured").mouseover(function () { alert("woo"); });
})(jQuery)();
</script>
}
it is basically a immediately executing function.

Does jQuery.load() load after <script> content is loaded?

Two questions:
Does jQuery.load() run after the content of <script> is completely downloaded?
If in case, there is a <script> in the document that will inject another <script> dynamically, does load() run after after the content of the 2nd script is downloaded or it will run after the original, non-dynamic content is loaded?
Thanks
The example for the 2) question is like that:
<html>
<head>
<script src="myscrip1.js"></script>
<script>
$(document).load( myscript2.functionA );
</script>
</head>
</html>
Where myscript.js will inject myscript2.js into the dom.
in which myscript2.js include the function myscript2.functionA
Obviously, I want to run myscript2.functionA after myscript2.js is loaded completely.
:)
The document ready event is fired when all of the resources referenced in the initial HTML have been downloaded (or timed out in case there are errors). If you dynamically inject a reference to another script (like the facebook api, google analytics, etc) it's readiness is undefined with relation to the document ready event.
If you want to check that your external script is ready you can check that an object that it creates has been loaded.
<script type="text/javascript">
var startAfterJqueryLoaded = function(){
if(typeof jQuery === "undefined" ) {
setTimeout( startAfterJqueryLoaded, 100 );
return;
}
// jQuery is ready, do something
}
startAfterJqueryLoaded();
</script>
Or if you have control of the script you are dynamically injecting you can establish a global function that it will call when it's ready.
<script type="text/javascript">
window.dynamicScriptIsReady = function(){
// do something
}
</script>
// Dynamic.js
// ...Setup whatever
window.dynamicScriptIsReady();
If you put the load event handler within the standard document ready event handler wrapper, it will ensure that the external script is loaded first. You should consider this standard practice. The solution is simple:
<script src="myscrip1.js"></script>
<script>
$(document).ready(function() {
$(document).load( myscript2.functionA );
});
</script>

Categories

Resources