Loading Javascript with XMLHTTP...?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • sneill@mxlogic.com

    Loading Javascript with XMLHTTP...?

    Using XMLHTTP and DOM I'm able to load new HTML page content.

    I'd now like to load small snippets of javascript with the HTML markup
    and have that <script> incorporated into the page. If any of the loaded
    script exists outside a function definition (eg: a call to a function),
    I'd like that code to be executed as soon as its added to the DOM.

    Can anyone suggest the best way to do this? I've Googled but not found
    anything comprehensive. Do I need to use the eval() method or is there
    a better way?

    Thanks,

    Steve

  • RobG

    #2
    Re: Loading Javascript with XMLHTTP...?

    sneill@mxlogic. com wrote:[color=blue]
    > Using XMLHTTP and DOM I'm able to load new HTML page content.
    >
    > I'd now like to load small snippets of javascript with the HTML markup
    > and have that <script> incorporated into the page. If any of the loaded
    > script exists outside a function definition (eg: a call to a function),
    > I'd like that code to be executed as soon as its added to the DOM.
    >
    > Can anyone suggest the best way to do this? I've Googled but not found
    > anything comprehensive. Do I need to use the eval() method or is there
    > a better way?
    >
    > Thanks,
    >
    > Steve
    >[/color]

    The best way is to add a script element with a src attribute:

    var oS = document.create Element('script ');
    oS.type = 'text/javascript';
    oS.src = 'someLink/cmd.js';

    <URL:http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/f39a6a56185a49c 1/a4c3d5dcce0a08e 6?tvc=1&q=docum ent.createEleme nt(%27script%27 )&hl=en#a4c3d5d cce0a08e6>

    But not all browsers may support the above. Also be careful of calling
    functions in any linked file as they must be downloaded & added to the
    document before they are ready to use. Adding a script element and then
    depending on its content being immediately available is risky.

    Any statements outside functions will be executed when the script is loaded.

    AFAIK, you can't modify the content of a script element dynamically.
    You can clone a script element that has statements outside functions and
    add it to some part of the document, but the statements will not be
    executed (at least not in Firefox or IE).


    --
    Rob

    Comment

    • Baconbutty

      #3
      Re: Loading Javascript with XMLHTTP...?

      I may be wrong about this, but you may also need to set the "defer"
      attribute to true.

      oS.defer="true" ;

      Comment

      • cosmic foo

        #4
        Re: Loading Javascript with XMLHTTP...?


        <sneill@mxlogic .com> wrote in message
        news:1122421863 .226152.181620@ o13g2000cwo.goo glegroups.com.. .[color=blue]
        > Using XMLHTTP and DOM I'm able to load new HTML page content.
        >
        > I'd now like to load small snippets of javascript with the HTML markup
        > and have that <script> incorporated into the page. If any of the loaded
        > script exists outside a function definition (eg: a call to a function),
        > I'd like that code to be executed as soon as its added to the DOM.
        >
        > Can anyone suggest the best way to do this? I've Googled but not found
        > anything comprehensive. Do I need to use the eval() method or is there
        > a better way?
        >
        > Thanks,
        >
        > Steve
        >[/color]

        you could add a hidden iframe to your page,
        and load whatever url you want into it.
        at the bottom of the iframe page, put some
        script that does something, such as call a
        function on the main page.


        Comment

        • sneill@mxlogic.com

          #5
          Re: Loading Javascript with XMLHTTP...?

          Thanks Rob,

          Actually, I've got the method you suggest working well in another area
          of my code. The problem is when I load HTML content dynamically using
          XMLHTTP -- how do I get the script added when it is received as
          "responseTe xt" from the XMLHTTP request?

          Perhaps I should parse the responseText and create new function
          objects?

          Hmm... tricky?

          Steve

          RobG wrote:[color=blue]
          > sneill@mxlogic. com wrote:[color=green]
          > > Using XMLHTTP and DOM I'm able to load new HTML page content.
          > >
          > > I'd now like to load small snippets of javascript with the HTML markup
          > > and have that <script> incorporated into the page. If any of the loaded
          > > script exists outside a function definition (eg: a call to a function),
          > > I'd like that code to be executed as soon as its added to the DOM.
          > >
          > > Can anyone suggest the best way to do this? I've Googled but not found
          > > anything comprehensive. Do I need to use the eval() method or is there
          > > a better way?
          > >
          > > Thanks,
          > >
          > > Steve
          > >[/color]
          >
          > The best way is to add a script element with a src attribute:
          >
          > var oS = document.create Element('script ');
          > oS.type = 'text/javascript';
          > oS.src = 'someLink/cmd.js';
          >
          > <URL:http://groups-beta.google.com/group/comp.lang.javas cript/browse_frm/thread/f39a6a56185a49c 1/a4c3d5dcce0a08e 6?tvc=1&q=docum ent.createEleme nt(%27script%27 )&hl=en#a4c3d5d cce0a08e6>
          >
          > But not all browsers may support the above. Also be careful of calling
          > functions in any linked file as they must be downloaded & added to the
          > document before they are ready to use. Adding a script element and then
          > depending on its content being immediately available is risky.
          >
          > Any statements outside functions will be executed when the script is loaded.
          >
          > AFAIK, you can't modify the content of a script element dynamically.
          > You can clone a script element that has statements outside functions and
          > add it to some part of the document, but the statements will not be
          > executed (at least not in Firefox or IE).
          >
          >
          > --
          > Rob[/color]

          Comment

          • Baconbutty

            #6
            Re: Loading Javascript with XMLHTTP...?

            I suppose "eval" might work.

            There is also a clue in RobG's answer.

            var oScript=documen t.createElement ("script");
            oScript.text=[[variable holding responseText]];
            oScript.defer=" true";
            document.getEle mentsById("head ")[0].appendChild(oS cript);

            Comment

            • sneill@mxlogic.com

              #7
              Re: Loading Javascript with XMLHTTP...?

              Thanks,

              I think that's it :)

              although I need to correct one line of your code...

              document.getEle mentsById("head ­")[0].appendChild(oS cript);

              should read...

              document.getEle mentsByTagName( "head­")[0].appendChild(oS cript);


              Steve

              Comment

              • RobG

                #8
                Re: Loading Javascript with XMLHTTP...?

                Baconbutty wrote:[color=blue]
                > I suppose "eval" might work.
                >
                > There is also a clue in RobG's answer.[/color]

                Setting the text attribute of the script element does indeed add and run
                the script as the OP requires - my test had a typo in the script that
                caused it to fail (dang browser thinks 'javascript' and 'javscript' are
                two different things).
                [color=blue]
                >
                > var oScript=documen t.createElement ("script");
                > oScript.text=[[variable holding responseText]];
                > oScript.defer=" true";
                > document.getEle mentsById("head ")[0].appendChild(oS cript);
                >[/color]

                The defer attribute does not necessarily affect when the script is run,
                it affects what the browser does while the script is loading and
                executing. I would expect the browser to load the entire script before
                executing any part of it.

                A test is to have a statement at the very start of a script file that
                calls a function at the very bottom of the file with a large amount of
                guff in between - I've never seen this fail (maybe I just haven't used a
                large enough file or slow enough connection) - though in practice I
                ensure all functions are loaded first).

                My reading of the HTML spec is that 'defer' tells the UA that it can
                load the script element content asynchronously because it doesn't
                generate any document content. In other words, don't defer
                parsing/rendering the rest of the document until the script is loaded
                (which is kinda contrary to what you might expect 'defer=true' to mean).

                "When set, this boolean attribute provides a hint to the user agent
                that the script is not going to generate any document content (e.g.,
                no "document.write " in javascript) and thus, the user agent can
                continue parsing and rendering."

                <URL:http://www.w3.org/TR/html4/interact/scripts.html#ad ef-defer>

                And in the index of attributes it says:

                "UA may defer execution of script"

                <URL:http://www.w3.org/TR/html4/index/attributes.html >

                The second reference seems to contradict the first somewhat, maybe the
                words 'while the rest of the document loads' should be added.

                'defer' is probably only of use if the script is in the body of the
                document or loaded from an external file and there is something else for
                the UA to get on with while it loads and executes.


                --
                Rob

                Comment

                • Baconbutty

                  #9
                  Re: Loading Javascript with XMLHTTP...?

                  Good catch.

                  Typing too hastily.

                  Comment

                  • Baconbutty

                    #10
                    Re: Loading Javascript with XMLHTTP...?

                    Thanks Rob. I think I have been using it primarily as a precaution,
                    without really thinking about it.

                    Comment

                    • ExGuardianReader

                      #11
                      Re: Loading Javascript with XMLHTTP...?

                      sneill@mxlogic. com wrote:[color=blue]
                      > Thanks Rob,
                      >
                      > Actually, I've got the method you suggest working well in another area
                      > of my code. The problem is when I load HTML content dynamically using
                      > XMLHTTP -- how do I get the script added when it is received as
                      > "responseTe xt" from the XMLHTTP request?
                      >
                      > Perhaps I should parse the responseText and create new function
                      > objects?
                      >
                      > Hmm... tricky?[/color]

                      No, this is how I update some UI elements. I have a servlet which
                      produces DOM modifying javascript.

                      Then in the onreadystatecha nge method of the XMLHttpRequest, when it
                      reaches success status, with HTTP status 200, I do

                      new Function(reques t.responseText) .call();

                      Comment

                      Working...