页面加载后加载脚本? [英] Loading scripts after page load?

查看:202
本文介绍了页面加载后加载脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与一家广告公司合作,我们会在其中标记某些网页以跟踪活动。我的客户希望在页面完全加载之后触发javascript标记以跟踪活动(以防止页面内容由于标记加载时间缓慢而加载缓慢)。

I work with an advertising company, where we tag certain pages to track activity. A client of mine wants to fire off a javascript tag to track activity AFTER the page has finished loading entirely (to prevent the page content from loading slowly due to slow tag load times).

在页面完全加载后应加载的示例标记是:

An example tag that should load AFTER the page has fully loaded is:

<script>document.write('<s'+'cript language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></s'+'cript>')</script>

我正在查看一些stackoverflow线程,我遇到了下面的实现,我认为它将起作用:

I was looking at some stackoverflow threads and I came across the below implementation which I think will work:

window.onload = function(){
  <script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>
};

我在自己的网页上对此进行了测试,我确实得到了标记,但我是想知道是否有任何替代或更强大的方法,理想情况下使用某种类型的jquery。

I tested this on my own webpage and I did get the tag to fire off, but I'm wondering if there are any alternate or more robust methods, ideally using jquery of some kind.

以下是客户端尝试的示例实现,但它似乎打破了他们的页面:

Below is a sample implementation that the client tried, but it seems to break their page:

<script>
jQuery(window).load(function () {$('<script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>').insertAfter('#div_name');});
</script>

我有一段时间没有完成JQuery,并希望我能在这里得到其他成员的一些意见。有没有其他方法可以在使用JQuery加载页面后调用上面的脚本?

I haven't done JQuery in a while and was hoping I could get some input from other members here. Is there any other way I can call the above script after page load using JQuery?

谢谢,

推荐答案

所以,这是行不通的:

window.onload = function(){
  <script language="JavaScript" src="http://jact.atdmt.com/jaction/JavaScriptTest"></script>
};

您无法自由地将HTML放到javascript中间。

You can't freely drop HTML into the middle of javascript.

如果你有jQuery,你可以使用:

If you have jQuery, you can just use:

$.getScript("http://jact.atdmt.com/jaction/JavaScriptTest")

随时随地。如果您想确保文档已完成加载,您可以这样做:

whenever you want. If you want to make sure the document has finished loading, you can do this:

$(document).ready(function() {
    $.getScript("http://jact.atdmt.com/jaction/JavaScriptTest");
});






在普通的javascript中,你可以动态加载脚本在任何时候你想这样:


In plain javascript, you can load a script dynamically at any time you want to like this:

var tag = document.createElement("script");
tag.src = "http://jact.atdmt.com/jaction/JavaScriptTest";
document.getElementsByTagName("head")[0].appendChild(tag);

这篇关于页面加载后加载脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆