简体   繁体   中英

Javascript, possible to check whether function exists in HTML <script> tags?

I have the following setup: a Javascript file (containing a google visualization function which Ajax will put into a new Div) and a vbscript file, containing implementation function for the Ajax call, which writes google visualisation javascript within tags.

In the Ajax call in the javascript file, I put the content of the Ajax call into a new div and append this to the container div. I then call one of the google javascript functions, which is the new content the Ajax call is adding to the html.

If i have an alert or setTimeOut() before the google javascript function call, it works. If i just immediately call the function it doesnt. So it appears there is some delay before the newly Ajax-added javascript code can be recognised.

Is there any elegant way to call the function without a timeout? I did write a while loop to keep looping until the new appended node was found, but the function call was still not recognised.

    function ProcessAjaxCall(DivID, ResponseText)
    {
        var NewDiv = document.createElement("div"); 
        NewDiv.id = "myscript";
        NewDiv.innerHTML = ResponseText;
        document.getElementById(DivID).appendChild(NewDiv);
        //alert('Function below only works when this outputs');
        MyGoogleJSFunction('Arg');
    }

So MyGoogleJSFunction is part of the code being written via the Ajax call and is within NewDiv.

This is because the parser cannot rerender the current page when JavaScript is executed (at least not yet). You'll have to give control back to let the browser load and execute the included script. One way of doing this, is using setTimeout (eg with a delay of 0 ); another is by closing and reopening the current script element, like Google Analytics does:

<script type="text/javascript">
    var _gaq=_gaq||[];
    _gaq.push(['_setAccount','UA-XXXXXXX-X']);
    _gaq.push(['_trackPageview']);
    (function(){
        var ga=document.createElement('script');
        ga.type='text/javascript';
        ga.async=true;ga.src='http://www.google-analytics.com/ga.js';
        var s=document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(ga,s);
    })();
    _qoptions={qacct:"p-c1rF4kxgLUzNc"};
    /* now close this script element, so we can use functions included
     * by the GA script */
</script>
<script>
    // …
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM