简体   繁体   中英

Displaying Script on Success with jQuery Ajax

I use this script (does a document.write, you can visit the src to see it), which spends time loading as soon as it is reached in the HTML sequence of my pages:

<script type="text/javascript" src="http://pkmncards.disqus.com/recent_comments_widget.js?num_items=25"></script>

This prevents anything after the script from loading for a second or two while it loads, so instead I want to load it via jQuery Ajax to prevent the hangup.

Here's what I've attempted:

var $j = jQuery.noConflict();
$j(document).ready(function () {
    $j.ajax({
        url: "http://pkmncards.disqus.com/recent_comments_widget.js?num_items=25",
        dataType: "script",
        success: function (data) {
            $j("#recent-discussion").html(data)
        }
    });
});

However I'm not handling the success properly. I see the request load, but it doesn't do anything. I want it to run the script and output the document.write into the target #recent-discussion.

I'm still searching for examples but can't figure out what I'm doing wrong... any help is much appreciated!

You cannot execute document.write after the page is loaded. Any script that you load via an AJAX call that uses document.write will not work correctly.

Your ajax call seems correct, and you don't actually need to do anything in the success callback - the script will have already started executing by then ( but not necessarily so ).

If it's not working, then check whether or not it was loaded correctly (maybe using an error callback in the ajax call). BTW is this script in the same domain as your main page? You can load scripts from different domains, but you can't normally make ajax calls to them (due to the same-origin policy).

I want it to run the script and output the document.write into the target #recent-discussion.

I don't think that's actually possible... If that's what your script need to do, and you can't change it, I'm afraid there's little you can do (short of monkey-patching document.write , that is).

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