views:

35

answers:

1

I use successfully the following code to load asynchronously some content into a web page:

 jQuery.noConflict();
        jQuery("#boxasync").load("box.php", "",
            function(responseText, textStatus, XMLHttpRequest) {
                if(textStatus == 'error') {
                    jQuery('#boxasync').html('There was an error making the AJAX request');
                }});

Now when trying to use the same code to load common sharebuttons (tweetme, facebook, digg) the webpage content is wiped out and the the browser is set in a sort of wait-state.

I have discovered that those sharebuttons sport some code embedding iframes (and javascript too, I'm afraid).

Could this be the reason jQuery .load is failing?

A: 

It's common for scripts designed for third-party invocation to use document.write() to output their content.

This is fine when loaded in a straight <script> element in the main page source, as at this point document.write merely adds output to the page at the position of the <script> that caused it. But it's no good after the page as loaded: there's no ‘write position’ for the content to end up in, so what JS does instead is to infer you meant to call document.open() to write a completely new document before calling write. This destroys the current page content.

You can try to ‘cheat’ third-party scripts by making your own function that overrides document.write, redirecting the strings passed to it to a variable which can then be output to the page using innerHTML/html(). But you may be better off extracting the guts of what the scripts do and doing it yourself. Reducing reliance on third-party scripts is a good thing because every time you use one, you're giving that party complete cross-site-scripting access into your security context.

In any case you should never use .load() or .html() to load content that includes <script>, as the results are highly unreliable.

bobince
What should be used to load something that may include <script>?
Riccardo
There is no reliable way. jQuery tries, but fails, to work around the cross-browser problems here. Keep your scripts and your markup separate. Try to keep script code completely static and execute it as and when you need to; if you really need to execute script returned from the server, use `eval` and keep it separate from returned markup.
bobince