3

我有以下脚本:

<script type="text/javascript">
$(document).ready(function(){ 
    document.write("<script type=\"text/javascript\" src=\"http://site.com/script.js\"><\/script>");
});
</script>

当我将它放入页面时,它会重定向到我不想要的脚本。

我想在我插入上面代码的地方回显这个 javascript 文件,所以一旦页面有它就会加载。目前,当我使用上面的脚本时,它只显示 javascript 文件的内容,而不是整个页面。

我希望它把它放到我放置这个脚本的页面中。

我这样做是为了使其调用的脚本基本上在页面加载后就位,因为目前该脚本导致页面在加载时暂停。

谢谢你。

4

5 回答 5

9

尝试:

$(document).ready(function(){ 
    $('body').append("<script type=\"text/javascript\" src=\"http://site.com/script.js\"><\/script>");
});

document.write在加载文档之前调用时将添加到文档中,但之后它将替换现有内容。

于 2011-11-08T10:51:26.210 回答
5

试试这个:

$(function() {

    $.getScript("http://site.com/script.js");
});

$.getScript 还允许您在脚本成功执行后调用函数。

于 2011-11-08T10:53:31.647 回答
4
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    </head>
    <body>
        <!-- content here... -->
    </body>
    <script>
        $.getScript('http://site.com/script.js');
    </script>
</html>

将脚本放在页面末尾以“延迟”脚本执行。使用 jQuery.getScript() 获取并执行脚本。

编辑为免生疑问,添加了查询。显然需要尽早允许$.getScript工作。

于 2011-11-08T10:53:40.070 回答
0

这可能是一种更清洁的方法:

$(document).ready(function(){ 
    $('<script>')
        .attr('type', 'text/javascript')
        .attr('src', 'http://www.example.com/script.js')
        .appendTo('body');
});

或者:

$(document).ready(function(){ 
    $('<script>')
        .attr({'type': 'text/javascript', 'src': 'http://www.example.com/script.js'})
        .appendTo('body');
});
于 2014-11-25T09:39:39.600 回答
-1

要将主页加载与广告加载分离,您可以将广告放在 iframe 中自己的页面中,或者类似地,使用 AJAX 下载脚本文件并在它出现时执行它。如果前者不足够,因为引用 URI 或其他原因,后者为您提供了一些灵活性:您可以使用字符串替换将“document.write”重写为其他内容,或者可能暂时将其替换为“document.write = custom_function; "

于 2011-11-08T10:53:05.757 回答