dougmacklin
dougmacklin

Reputation: 2610

Wait For head.ready() and $(document).ready(), Then Execute

I want to execute some code after the document is ready AND all script loading is complete. I use head.js to load the scripts:

$(document).ready(function () {
    head.js("script1.js", "script2.js", function() {
        // code to execute
    });
});

Doing it this way makes starting to load the scripts wait for $(document).ready(). It seems like it would be better to start loading the scripts as soon as possible to avoid a performance drop.

Is there a better way to make sure the document AND the scripts are fully loaded prior to executing a block of code?

Upvotes: 0

Views: 4786

Answers (4)

jfriend00
jfriend00

Reputation: 707646

You are making the way too complicated. If you want the document to load first, then your scripts to load and then you can execute some code, then just put script tags at the end of the document right before </body> like this:

<head>
</head>
<body>

Your regular HTML content here
<script src="script1.js"></script>
<script src="script2.js"></script>
<script>
// Put code here that you want to execute when document and scripts are ready
</script>
</body>

You don't need dynamic loading with callbacks for the simple cause you've described.

Upvotes: 0

Kevin B
Kevin B

Reputation: 95047

It's better to swap the code around.

head.js("script1.js", "script2.js", function() {
    $(document).ready(function () {
        // code to execute
    });
});

the scripts start loading immediately, then when they are done, they wait until the document is ready and then begin executing.

It would be even better if you moved the script to before the closing body tag and removed the domready handler all together.

Upvotes: 1

algorhythm
algorhythm

Reputation: 8728

Put your $(document).ready() code at the and of all other scripts?!

Upvotes: 0

Jai
Jai

Reputation: 74738

You can use .load to load everything first then execute everything:

$(window).load(function () {
    head.js("script1.js", "script2.js", function() {
    // code to execute
    });
});

Upvotes: 0

Related Questions