Search code examples
jquerytimeoutdelayexecute

Execute jQuery block last


Before calling my question a duplicate of this one, please read my question through.

I have a set of demo pages for my blog posts. These pages can have CSS, HTML, jQuery/JS, or any combination of the three. The page is organized as follows:

<div id="page-wrapper">
<style type="text/css">
//CSS here.
</style>

<!--Include jQuery here-->
<script type="text/javascript">
//JS here
</script>

<!--Demo HTML would go here-->
</div>

(I know style tags in the body are bad, I have my reasons.)

After the page-wrapper div, I include a JavaScript source file that creates a "View Source" link/button.

The problem arises because the demo JavaScript may contain changes to CSS, and these changes show up in the demo HTML (e.g. style="color: #ff0000; ") since the code is being "gotten" by the JavaScript source file at the end, as follows:

var sourceCode = "<!DOCTYPE HTML>\n<html>" + $('html').html() + "\n</html>";

I want the demo jQuery to execute last; that is, after the source file inclusion is executed. I can't do the following things:

  1. Move the source-file inclusion/reference to the <head> tags because jQuery is included in the body. This is so that source code viewers know I'm using jQuery.
  2. Add code to the demo JavaScript for it to wait, since source code viewers would be confused.
  3. Make the demo JavaScript wait too long since viewers are impatient :)

Is there a solution?


Solution

  • It looks like you're creating something like jsFiddle or jsBin.

    What you can do is make sure that the JS code that you want to inject into your template gets injected into a function callback. The onload event sounds like it should do what you want.

    <div id="page-wrapper">
        <style>
            <!-- ### demo CSS -->
        </style>
        <script>
            (function ($) {
                $(window).load(function () {
                    <!-- ### demo JS -->
                });
            })(jQuery);
        </script>
        <!-- ### demo HTML -->
    </div>
    

    Depending on your implementation, that may not work, so you can try triggering a custom event callback instead, if onload doesn't cut it.

    <script>
        (function ($) {
            $(window).on('my.custom.event', function () {
                <!-- ### demo JS -->
            });
        })(jQuery);
    </script>
    <!-- ### demo HTML -->
    <script>
        jQuery(window).trigger('my.custom.event');
    </script>