jasono
jasono

Reputation: 213

Best way to delay js loading?

I'm using a bootstrap theme that requires a few javascript files. On some of my pages I load quite a bit of content from the server which means not all the html will be on the page at the time the javascript files are evaluated.

This prevents the event handlers from binding to the html that's loaded after the javascript is evaluated. So far I've fixed the problem by loading the scripts after the ajax call is finished, but this seems pretty hokey to me. Here's my function:

$.get("/path/to/rest/call", function(data) {
    $('#htmlElement').html(data);
}).done(function() {
    $.getScript("/path/to/js/file.js");
});

I feel like there's a better way to do this. Is there?

Upvotes: 0

Views: 559

Answers (1)

jfriend00
jfriend00

Reputation: 707218

There may be a cleaner way of solving this than dynamically loading the metroui library. It looks like it depends upon jQuery's .ready() to know when the page is loaded and when it can initialize it's things. But, that doesn't work for you because you are dynamically loading content via Ajax.

What you can do is you can hold off the jQuery ready() notification until after your ajax content is loaded. This will then hold off the firing of metro's initialization until after your dynamic content is loaded. This would allow you to load metro in a stock <script> tag in the <head> section like their doc suggests. The way this works is you add this to the <head> section, after jQuery is loaded:

<script>
    jQuery.holdReady(true);
</script>

Then, after your ajax code has succesfully completed, you do this (from the success handler, after you've put your new content into the page):

 jQuery.holdReady(false);

which then releases jQuery to call it's .ready() handlers and metro will do it's thing after your content is loaded.

See jQuery doc for jQuery.holdReady(...).

Upvotes: 1

Related Questions