www.webdeveloper.com
Results 1 to 10 of 10

Thread: Dynamically loading JavaScript files

  1. #1
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773

    Dynamically loading JavaScript files

    I'm trying to sort out a method for dynamically loading JavaScript files. It seems that when I try to use anything declared in the "included" file right after I call the function to include the file, the file hasn't been loaded. The sample code I'm working with below:
    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    
    <html>
      <head>
        <title>Testing Importing JS Files</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <script type="text/javascript">
        <!-- begin hiding
          function createScript(src) {
            var el = document.createElement("script");
            el.type = "text/javascript";
            el.src = src;
            return el;
          }
          
          function getHeadNode() {
            return document.getElementsByTagName("head")[0];
          }
          
          function require(src) {
            getHeadNode().appendChild( createScript(src) );
          }
          
          require("test.js");
          alert( Foo );
        // end hiding -->
        </script>
      </head>
      <body>
        
      </body>
    </html>
    The contents of test.js:
    Code:
    var Foo = "bar";
    alert("test.js loaded!");
    I would like it so the first alert you see is "test.js loaded!" and the second alert you see is "bar". Currently it's backwards, and I can only assume this is because the browser loads test.js asynchronously. Is there any way, without using AJAX, to dynamically append SCRIPT elements or JavaScripts to the page, prior to the onload event, and have the browser load the script synchronously?

  2. #2
    Join Date
    Nov 2008
    Location
    Akron, OH
    Posts
    233
    Try moving the ones you want to control to the bottom of the page, after </body> before </html>.

    <body>

    </body>
    <script>
    require("test.js");
    alert( Foo );
    </script>
    </html>

  3. #3
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773

  4. #4
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    here's a couple soultions that might work for you:

    1. hard-code a callback as the last line of your included scripts, and delay the main execution by placing it in a function named by the call back.
    example:

    Code:
    //in include1.js:
     function el(tid) {return document.getElementById(tid);}
    // ... whatever other libs or code you got in there. last line:
     if(window.myCallBack){ myCallBack();}
    
    //in html page:
    <script>
    function myCallBack(){
      el("welcome").innerHTML = "page visited at "+Date();
    }
    </script>
    its an asynch model at that point.



    your pattern will work with a different adder.
    adding a script tag via the dom is more or less asych.
    there are certain indicators and events in some browsers that can be used to determine when a script loads.

    but it's complicated and inconsistent, and like my simple scheme above; still async.


    there is a way to wait for the script tag to be included is loaded before continuing.

    Our old friend document.write can be used during load to accomplish this.
    while often frowned on, document.write deserves some credit because it works, and works well in every browser. it's a mainstay of the advertising industry.

    try this adder:
    Code:
          function require(src) {
            document.write("<script type='text/javascript' src='"+src+"'><\/script>" );
          }
    
          alert( window.Foo );
          require("test.js");
          alert( Foo );

  5. #5
    Join Date
    Oct 2008
    Location
    U.S.
    Posts
    726
    setTimeout("alert( Foo )",1);

    What about using a slight delay???

  6. #6
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Quote Originally Posted by astupidname View Post
    setTimeout("alert( Foo )",1);

    What about using a slight delay???
    if the tags were hard-coded in the html, you could probably hop like that, but when adding the tags using the method in the OP, the script must load+parse within 1ms to work.

    if you sometimes have to wait 10 seconds to get the script, a pre-coded timeout value will likely be either too short to be safe or too long not to cause an annoying delay.

    using the synch method i posted will freeze the browser while the script loads, but you kinda have to if you need that script's code to continue...

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,290
    Why not a simple
    Code:
    window.onload=function(){
    // when it loads I will run...
    }
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  8. #8
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    The idea is to dynamically load JavaScript files so you don't need to manually add <script> tags to your HTML source, and to cut down on the total file size for the JavaScript library. I've considered using callbacks, like rnd me suggested, but there comes a point and time when the code you write is just too obfuscated from what it really does that it isn't worth it.

    I was really looking for a way to add JavaScript files while the page is loading using a synchronous process, but that appears impossible unless you use a synchronous XMLHttpRequest.

    Thanks for all the suggestions!

  9. #9
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    Quote Originally Posted by toicontien View Post
    The idea is to dynamically load JavaScript files so
    I was really looking for a way to add JavaScript files while the page is loading using a synchronous process, but that appears impossible unless you use a synchronous XMLHttpRequest.

    Thanks for all the suggestions!
    does this not does exactly what you describe?

    Code:
        function require(src) {
            document.write("<script type='text/javascript' src='"+src+"'><\/script>" );
          }
          alert( window.Foo );  //undefined
          require("test.js");  //test.js defines Foo
          alert( Foo );

    you might also try to poke around the ajile framework, and see how they do it...
    Last edited by rnd me; 12-04-2008 at 02:41 PM.

  10. #10
    Join Date
    Feb 2003
    Location
    Michigan, USA
    Posts
    5,773
    No. Once the script tag is written to the document, the browser continues executing scripts while downloading the other script. Did some searching on google and found that only a synchronous XMLHttpRequest does what I want it to do.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles