1

In my ajax based app, specifically a GWT app, it has divs with scripts on the index HTML that is hidden. This are ads that are re-located as the app is fully loaded. The problem with this approach is that the ad scripts are fetched first before the app is fully loaded causing a delayed effect or slow loading of the app.

Is there a way to delay loads those scripts inside those divs such that the app may load gracefully first and the user experience may not be affected by those fetching of scripts and its execution prior to complete page load?

e.g.

<script src="gwtapp.nocache.js"/>
<div id="ad1">
  <script>...</script>
</div>

There are quite few divs that needs to be delayed also in my app. Is there a way for jQuery to make the div not load yet and just trigger it programatically when time is ready.

1
  • 1
    you could use some short javascript listening to the body.onload event. When the event is fired you just add the script-tag dynamically to your dom. A differenct approach would be to encapsulate your included script in a function and call it when the onload-event is fired. This way the script can be executed directly after the body has completed loading without having to fetch the actual script from the server first. Commented Mar 16, 2015 at 9:20

2 Answers 2

1

As CorwinCZ mentioned you can use ready function. And use jQuery.getScript() to load a JavaScript file from the server using a GET HTTP request, then execute it.

   $(function() {
      $.getScript( "gwtapp.nocache.js" )
      .done(function( script, textStatus ) {
        console.log( textStatus );
      })
      .fail(function( jqxhr, settings, exception ) {
        console.log( "ERROR" );
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

1

You can use jQuery .ready() - put everything inside the .js file to this function. Like this:

$(document).ready(function() {
  //code here
});

Function .ready() waits for complete DOM tree load and creation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.