Design pattern for loading content via Ajax on initial page load - javascript

One screen I have needs to render entirely before it calls ajax to start a long-running task. I.e. loading the layout before loading in a report that takes 10+ seconds (relies on web services).
I can do this by adding a separate script to the page and calling the Ajax when that script is loaded, but is that the best design? E.g.
_myreport.js:
$( document ).ready(function() {
var report = {
load: function() {
//test for report-container and run Ajax load if it exists
}
}
report.load();
});
I might have several pages for this and I don't particularly like having multiple scripts for multiple different pages. Or I might want to re-use scripts across multiple pages when the Ajax call may or may not be required (and the container may or may not exist). I can check for the existence of the container before running the Ajax but to me this doesn't feel like a good design. I'd like to call it when required, not call it every page load and then test if it's applicable via the container existing.
I tried putting a small call to the function in the body after the container, but this results in an error as the report.load() function has not yet been defined:
template.phtml
<div id='report-container'></div>
<script>
$( document ).ready(function() {
report.load();
});
</script>
What is a common/standard and clean way of doing this that I can re-use across multiple applications?

report.load has not been defined because it's warped in $( document ).ready.
You are trying to call it after the report-container has loaded but before entire DOM has.
If you declare your ajax loading function outside of $( document ).ready, it will be avalable.
Same with the call to it, you are running a script after the div loads, but becouse it's wrapped in $.ready, instead of executing right away, it waits for the rest to load...
Something like this should work
// not wrapped in $( document ).ready
var report = {
load: function() {
// not sure if you need to test for container, this function is called after it loads
//run Ajax
}
}
<div id='report-container'></div>
<script>
// not wrapped in $( document ).ready
report.load();
</script>

Related

Load javascript faster in the first load itself

I have a temperature widget from http://www.accuweather.com/en/ae/dubai/323091/weather-forecast/323091 and by default it's showing in the website as "DUBAI, AE" on the widget.
I need to make it "DUBAI, UAE" and for that I used the script
$( window ).load(function() {
$('.aw-current-weather-inner h3').replaceWith( "<h3>Dubai, UAE</h3>" );
});
But while loading the website, it's taking time to load as DUBAI, UAE. Initially the site loads as DUBAI, AE.
I need to see it as Dubai, UAE in the first load itself.
Use document.ready, it will take bit less time as compared to window.load (it waits to load whole the content like images,videos). In your case, there is only text so you can use document.ready.
$( document ).ready(function() {
$('.aw-current-weather-inner h3').replaceWith( "<h3>Dubai, UAE</h3>" );
});
You cab use .ready event of jQuery
$(document).ready (function(){
})
And even i don't think $(window).unload() will take time, this might been the response issue from the server.
If it'll not work, you can make them hide for initial time and then show on loading on the page using .hide() and .show()

Execute jQuery after Other JS file Dynamically loads content

I'm working to modify some content which is dynamically loaded via another script(let's call is script #1) onto my site. Script #1 loads some markup and content and I've been using the setTimeout() function to call my script (Script #2) using a delay of a few seconds, in order to wait to be sure that Script #1 has executed and the content is present in the DOM.
My issue is that Script#1 has different loading times, based on the server load and can be slow or fast depending on these factors, and right now, playing it safe with setTimeout() I'm often left with a second or two where my scripts are still waiting to be fired and Script #1 has already loaded the content.
How can I execute my script as soon as Script#1 successfully loads it's dynamic content?
I've found this post which does seem to address the same issue but using the setInterval function as #Matt Ball has laid out there doesn't work at all for some reason. I'm using the code below where 'div.enrollment' is meant to find in the DOM which is dynamically loaded and execute..
jQuery(window).load(function ($)
{
var i = setInterval(function ()
{
if ($('div.enrollment').length)
{
clearInterval(i);
// safe to execute your code here
console.log("It's Loaded");
}
}, 100);
});
Any help on guidance on this would be greatly appreciated! Thanks for your time.
It seems that the healcode.js is doing a lot of stuff. There is a whole lot of markup added to the <healcode-widget> tag.
I would try to add another tag with an id inside and test for its existence:
<healcode-widget ....><div id="healCodeLoading"></div></healcode-widget>
Test in an interval for the existence of healCodeLoading inside <healcode-widget>: (Assuming jQuery)
var healCodeLoadingInterval = setInterval(function(){
var healCodeLoading = jQuery('healcode-widget #healCodeLoading');
if (healCodeLoading.length == 0) {
clearInterval(healCodeLoadingInterval);
// Everything should be loaded now, so you can do something here
}
}, 100);
healcode.js should replace everything inside <healcode-widget></healcode-widget> during init. So, if your <div>-element is no longer inside, the widget has loaded and initialized.
Hope that helps.
If you just want to load some markup and content and then run some script afterwards, you can use jQuery. You should use something like the following in script#1 to run a function in script#2
$.get( "ajax/test.html", function( data ) {
// Now you can do something with your data and run other script.
console.log("It's Loaded");
});
The function is called, after ajax/test.html is loaded.
Hope that helps

Jquery event in manipulated content by another script

I have page where an external script manipulates the content. The completion of manipulation takes a while depending on connection speed, etc.
What i want to do is to change attributes of some elements in manipulated content. When i try
$('#confirmButton').remove();
it doesn't work as the button does not exist at the time of running this jquery function.
What can i do to wait for the manipulation to complete, and then run my Jquery manipulations?
I was able to solve this by calling the external script from within jquery
$.getScript("http://externalscript.js", function(){
//alert("Script loaded and executed.");
//call remove function a bit later in case manipulation takes long
window.setTimeout(function (){ $('#confirmButton').remove(); }, 500);
});

extend jquery load() function to show spinner inside div

is there a way to alter .load behavior so that it load a spiner inside any div that is loading data ?
example
<div class='content lside'></div>
<script>
$(document).ajaxStart(function() {
$('body').append('<div class="notice" style="position:fixed;top:40%;left:30%;z-index:99999;"id="loadingspin">loading</div>'); });
$(document).ajaxStop(function() {
$('#loadingspin').fadeOut().remove();
});
$('.content').load("<?=base_url();?>booking/<?=$day?>");
</script>
i use above script.
but what i actually want is that when ever ajaxstart the content of $('.content') is replaced with spinner until it finish loading the new content.
so is there a way i can extend .load to do that by it self and replace the ajaxstart,
so where ever $(div).load() is called a $(div).html('spiner'); is fired.
if not, is there a way .ajaxstart can reference the div that the content will be loaded into ?
please note: im currently using .ajaxstart and .ajaxstop in my header script in all my webpage to handle showing the spinners in general, but i want to replace it/extend it with div specific solution that would still work on any page without further editing into each and every ajax request.
thanks
probably something like this should do the trick. Override jQuery's prototype and save the old function.
(function(){
var oldLoad = jQuery.fn.load;
jQuery.fn.load = function( url, data, complete ){
/*
* do your stuff
*/
oldLoad.call( jQuery, url, data, complete );
}
})();
That changes the globally available jQuery.load() method for the whole page so »your stuff« should be executed even if other scripts call that method, a least after your re-definition of that function is parsed.

Execute $(document).ready() after $.load(), is that possible or is there an Alternative

I have page with a form and a table (to show results of the saved data using the form).
The form uses ajax to submit the data, data saved and the table should be reloaded afterwards.
The problem is that the table (which is loaded using AJAX($.load)) is loaded after the execution of $(document).ready(). which implies that the table does not have the required functionality.
Is there any approach where i can postpone the execution of $(document).ready() until the AJAX finish its loading, or shall i use a complete different approach like using iframe?
below is an example of my problem:
$(document).ready(function(){
//some code here that needed for the html in table.html e.g. datepicker, chosen, jqueryui, etc
});
<form>
//Inputs with a button to submit using ajax, where the result is displayed using table.php
</form>
<div id="tableOfContent"></div>
<script>
$('#tableOfContent').load("table.php");
</script>
You can do
$('#tableOfContent').load("table.php",function(){
//completed load actions here
});
But you should note that if you load images, they will not be loaded yet. If that is the case, you can make the contents of table.php initially hidden and do the same again inside for $('#tableOfContent img').load(). This would work for 1 image; multiple images is a bit more complicated, but feel free to ask if that is what you are looking for :)
You can delay the ready event using jQuery.holdReady():
$.holdReady(true);
// Do your custom stuff... the document may already be loaded.
$.holdReady(false); // Now the ready event will fire as soon as the DOM is loaded.
See http://api.jquery.com/jQuery.holdReady/
document.ready is called when the HTML of the page has finished loading, there's no two ways about it.
What you can do, however, is use live binding, which will attach handlers to elements that are not yet on the page.
Example:
$(".datepicker").live("click", function() {
$(this).datepicker();
})
Updated for jQuery >1.7 (this is also faster)
$("#tableOfContent").on("click", ".datepicker", function() {
$(this).datepicker();
})
Load the table data from within the ready function and use the complete event of the load() function to call the remainder
$(document).ready(function() {
// click bindings etc ..
$('#tableOfContent').load("table.php",function() {
// things to do once the table is loaded
});
});
load() documentation
$(document).ready() should be used for scripts that should execute, well, when document is ready.
If you need to execute something after an ajax call, you may write everything within a function and call it with the ajax callback.
function what_i_need() {
// bla bla
}
<script>
$('#tableOfContent').load("table.php", {}, what_i_need);//code had syntax error; '{)'
</script>
I'm not sure. Plus, you can call the function when document is ready too.
$(document).ready(function(){
what_i_need();
});

Categories