How to force scripts include order

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • oshany
    New Member
    • Dec 2009
    • 1

    How to force scripts include order

    HI,
    I have a very annoying problem - I have 2 external js file - script1.js and script2.js.
    script2.js depends on script1.js being executed 1st. So, in the relevant jsp I have:
    <html>
    ...
    <script src="script1.js "></script>
    <script src="script2.js "></script>
    ....
    </html>

    Usually it works fine.
    However, from time to time, for some reason, script2.js is executed before script1.js, and of course this causes an error.

    I'm working with IE7/8. Both show the problem ,but IE8 does it much more often.
    Has anyone ever encountered this problem ? is there a way to force the order ?

    Thanks, Ofer.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    usually this is enough for execution order. except when script 1 has not finished loading due to some Events or asyncronous AJAX calls. but I can’t tell without looking at the code (link to the page).

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      How about including script2.js within script1.js as the last line?

      Either add it to the head after page load, or use document.write during page load.

      Does that help?

      Comment

      • rnd me
        Recognized Expert Contributor
        • Jun 2007
        • 427

        #4
        if both are in the <head>, the rules are very explicit that script1 MUST complete or error before script2 is evaluated. It's been that way for a long time, and i hope that it doesn't change.

        the defer attrib and dom-adders break the rule for the better.

        if all else fails,
        you can paste this into the very bottom of script1:

        Code:
        document.write("<script src='script2.js'><\/script>")
        if you use a document.create Element("script ") type approach, be aware that window.onload() can fire before the script finished downloading...

        Comment

        Working...