0

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?

DaveO
  • 1,909
  • 4
  • 33
  • 63

1 Answers1

1

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>
Beckafly
  • 411
  • 2
  • 5
  • Thanks - could you explain why (this is a general question) the javascript can run in the body when it depends on an external library - is JS in the body only run after all external JS scripts are loaded and parsed? – DaveO Oct 04 '14 at 02:02
  • Well, the links to DOM manipulation libraries, like jquery are usually included in the head, so they will load first. By the time anything gets called form the body, it will be available. – Beckafly Oct 04 '14 at 07:33
  • Thanks Byaxy, also found more info here: http://stackoverflow.com/a/8996894/422611 – DaveO Oct 04 '14 at 10:15