0

I am trying to do something that uses the async loading pattern as bellow:

<div id="mydiv">
    <script type="text/javascript">
        var test = .......;
        function() {
            var js = document.createElement('script');
            js.async = true;
            js.src = 'myscript.js';
            var first = document.getElementsByTagName('script')[0];
            first.parentNode.insertBefore(js, first);
         })();
    </script>
<div>

Then inside myscript.js I work on the assumption that the div with id mydiv is guaranteed available when it myscript.js is executed. Is this assumption valid? It sounds really should be the case. But i sometimes run into situation the code couldn't find the div inside myscript.js.

Also regarding the general page loading. does all the tags get loaded first? what happens when this async loading pattern happens? does it get loaded after all the original tags gets loaded first?

Thanks,

0

1 Answer 1

1

Put the script element outside the div element, after it. Elements are created in sequential order, and script elements inside the body are executed as they are created, so this will guarantee that the div will be available when the script is executed.

This also avoids a nasty error on IE where modifying the elements containing a script block from within the script block causes it to refuse to render the page entirely.

Sign up to request clarification or add additional context in comments.

4 Comments

you mean like: <div/> <script/> I didn't notice the IE bug you mentioned. Either way, could the missing Div problem I described be possible?
@userrandomnumbers: I'm not sure what you mean.
"But i sometimes run into situation the code couldn't find the div inside myscript.js." As described in my original post.
@userrandomnumbers: Yeah, I read your comment before you were done editing it. I've never seen the problem you're running into, but putting the script element after the div will guarantee that everything loads in the correct order.

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.