良好的实践方法,通过ajax加载JavaScript [英] Good practice method for loading JavaScript via ajax

查看:133
本文介绍了良好的实践方法,通过ajax加载JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我是相当新的AJAX

Disclaimer: I'm fairly new to AJAX!

我环顾四周,我不知道该用用Ajax加载的JavaScript方法。

I've looked around, and I'm not sure which method to use to load javascript using ajax.

我使用Ajax来要求每一个需要他们自己的6-10短方法页。总共将有可能5-6这些网页,所以一共有大约35岁以上的方法。

I'm using ajax to request pages that each require their own 6-10 short methods. In total there will be maybe 5-6 of these pages, so an approximate total of 35+ methods.

我会preFER访问必要的JavaScript因为每个页面需要加载。

I would prefer to access necessary javascript as each page that requires it loads.

我已经看到了一些方法,我不知道哪一个最适合我的需要:

I've seen a few methods, and I'm not sure which one would best suit my needs:

  1. 在HEAD部分包括一个空的script元素,并通过操纵src属性。 DOM的。

  1. Include an empty script element in the head, and manipulate the src attribute via. the DOM.

通过创建一个新的脚本元素。 DOM并追加到了document.body的(这听起来一样#1)。

Create a new script element via. the DOM and append it to the document.body (this sounds the same as #1).

由于我是新来的Ajax和Web开发总的来说,我很好奇,每种方法我已经错过了风风雨雨以及任何方法。

As I'm new to ajax and web development in general, I'm curious as to the ups and downs of each method as well as any methods I've missed.

有些担忧是: - 将会缓存副本中使用,或将脚本下载一个Ajax请求时各一次。请注意,脚本将是静态的。 -browser兼容性。我使用的浏览器,但这个程序将在整个IE浏览器的版本中使用> = 7和Firefox浏览器。

Some concerns are: -Will a cached copy be used or will the script download each time an ajax request is made. Note that the scripts will be static. -Browser compatibility. I use Chrome, but this app will be used across versions of IE >= 7 as well as Firefox.

推荐答案

在一个jQuery的环境下,我会使用 getScript加入脚本()。你说的没错想知道关于缓存 - getScript加入包括缓存清除功能(主要是为了战胜咄咄逼人的IE缓存中,但当然,在其它情况下非常有用)。您可以执行相当于一个非缓存破获 getScript加入是这样的:

In a jQuery environment, I'd use getscript(). You're right to wonder about the cache -- getscript includes a cache-busting feature (designed primarily to defeat aggressive IE caching, although of course useful in other scenarios). You can perform the equivalent of a non-cache-busted getscript like this:

$.ajax({
    cache: true,
    dataType: "script",
    url: "your_js_file.js",
    success: yourFunction
});

这篇关于良好的实践方法,通过ajax加载JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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