Google AdWords Conversion Services Issue - Asynchronous Conversion Code

≯℡__Kan透↙ 提交于 2019-12-02 01:33:40

The reason why you can't just re-execute the script is—as you may have noticed—is that it uses document.write, which should not be called after the document has already loaded.

One possible solution is to just fire off the GIF request yourself, as you mentioned. If you really want to re-execute the script, there's the possibility of redirecting document.write.

Here's the general idea of how this could be done—this fragment would be placed somewhere where you reload new content into your page. It assumes that you use jQuery and have already loaded the new page content into $newContent and have marked all script tags that need to be executed on reload with class="ajax-exec". What it does is to execute inline script directly and use jQuery's $.ajax function with dataType: script. It then waits until all external scripts have executed and appends the redirected output to a hidden div.

This works for us, but comes without warranty (:

// Execute js from the new content (e.g. AdWords conversions tags).
// We redirect document.write to a string buffer as we're already
// done loading the page at this point.
var buf = '';
var writeMethSave = document.write;
$('div#lazyload-buf').remove();
var done = {};

document.write = function (string) {
        buf += string;
};

$newContent.filter('script.ajax-exec').each(function () {
    var url = $(this).attr('src');
    if (url) {
        // External script.
        done[url] = false;
        $.ajax({
            url: url,
            dataType: "script",
            success: function () {
                done[url] = true;
            }
        });
    } else {
        // Inline script.
        $.globalEval($(this).html());
    }
});

function checkForDone () {
    for (var url in done) {
        if (!done[url]) {
            setTimeout(checkForDone, 25);
            return;
        }
    }
    // All done, restore method and write output to div
    document.write = writeMethSave;
    var $container = $(document.createElement("div"));
    $container.attr('id', 'lazyload-buf');
    $container.hide();
    $(document.body).append($container);  
    $container.html(buf);
};

setTimeout(checkForDone, 25);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!