您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

适用于网页的 Application InsightsApplication Insights for web pages

了解网页或应用的性能和使用情况。Find out about the performance and usage of your web page or app. 如果将 Application Insights 添加到页面脚本,可以获取页面加载和 AJAX 调用的时间、浏览器异常和 AJAX 失败的计数和详细信息,以及用户和会话计数。If you add Application Insights to your page script, you get timings of page loads and AJAX calls, counts, and details of browser exceptions and AJAX failures, as well as users and session counts. 所有这些信息可按页面、客户端 OS 和浏览器版本、地理位置和其他维度细分。All these can be segmented by page, client OS and browser version, geo location, and other dimensions. 可以针对失败计数或页面加载缓慢情况设置警报。You can set alerts on failure counts or slow page loading. 并且通过在 JavaScript 代码中插入跟踪调用,可以跟踪网页应用程序的不同功能的使用情况。And by inserting trace calls in your JavaScript code, you can track how the different features of your web page application are used.

可以在任何网页中使用 Application Insights - 刚刚添加了 JavaScript 的简短片段。Application Insights can be used with any web pages - you just add a short piece of JavaScript. 如果 Web 服务是 JavaASP.NET,则你可以将服务器端 SDK 与客户端 JavaScript SDK 结合使用,以全方面地了解应用的性能。If your web service is Java or ASP.NET, you can use the server-side SDKs in conjunction with the client-side JavaScript SDK to get an end-to-end understanding of your app's performance.

添加 JavaScript SDKAdding the Javascript SDK

  1. 首先需要一个 Application Insights 资源。First you need an Application Insights resource. 如果你尚未获得资源和检测密钥,请遵照有关创建新资源的说明If you don't already have a resource and instrumentation key, follow the create a new resource instructions.
  2. 从你要将 JavaScript 遥测数据发送到的资源复制检测密钥。Copy the instrumentation key from the resource where you want your JavaScript telemetry to be sent.
  3. 通过以下两个选项之一,将 Application Insights JavaScript SDK 添加到网页或应用:Add the Application Insights JavaScript SDK to your web page or app via one of the following two options:

重要

只需使用下述方法之一即可将 Application Insights JavaScript SDK 添加到应用程序。You only need to use one of the methods below for adding the Application Insights JavaScript SDK to your application. 如果使用基于 NPM 的设置,请不要使用基于代码片段的设置。If you use the NPM based setup, don't use the snippet based setup. 反之亦然,在使用基于代码片段的方法时,请不要使用基于 NPM 的设置。The same goes for the reverse scenario when using the snippet based approach, don't also use the NPM based setup.

基于 NPM 的设置NPM based setup

import { ApplicationInsights } from '@microsoft/applicationinsights-web'

const appInsights = new ApplicationInsights({ config: {
  instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE'
  /* ...Other Configuration Options... */
} });
appInsights.loadAppInsights();

基于代码片段的设置Snippet based setup

如果应用程序不使用 NPM,则可以通过直接使用 Application Insights 来检测网页:只需将此代码片段粘贴到每个页面的顶部即可。If your app does not use NPM, you can directly instrument your webpages with Application Insights by pasting this snippet at the top of each your pages. 最好是将它用作 <head> 节中的第一个脚本,以便它可以监视所有依赖项存在的任何潜在问题。Preferably, it should be the first script in your <head> section so that it can monitor any potential issues with all of your dependencies.

<script type="text/javascript">
var sdkInstance="appInsightsSDK";window[sdkInstance]="appInsights";var aiName=window[sdkInstance],aisdk=window[aiName]||function(e){function n(e){t[e]=function(){var n=arguments;t.queue.push(function(){t[e].apply(t,n)})}}var t={config:e};t.initialize=!0;var i=document,a=window;setTimeout(function(){var n=i.createElement("script");n.src=e.url||"https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js",i.getElementsByTagName("script")[0].parentNode.appendChild(n)});try{t.cookie=i.cookie}catch(e){}t.queue=[],t.version=2;for(var r=["Event","PageView","Exception","Trace","DependencyData","Metric","PageViewPerformance"];r.length;)n("track"+r.pop());n("startTrackPage"),n("stopTrackPage");var s="Track"+r[0];if(n("start"+s),n("stop"+s),n("setAuthenticatedUserContext"),n("clearAuthenticatedUserContext"),n("flush"),!(!0===e.disableExceptionTracking||e.extensionConfig&&e.extensionConfig.ApplicationInsightsAnalytics&&!0===e.extensionConfig.ApplicationInsightsAnalytics.disableExceptionTracking)){n("_"+(r="onerror"));var o=a[r];a[r]=function(e,n,i,a,s){var c=o&&o(e,n,i,a,s);return!0!==c&&t["_"+r]({message:e,url:n,lineNumber:i,columnNumber:a,error:s}),c},e.autoExceptionInstrumented=!0}return t}(
{
  instrumentationKey:"INSTRUMENTATION_KEY"
}
);window[aiName]=aisdk,aisdk.queue&&0===aisdk.queue.length&&aisdk.trackPageView({});
</script>

将遥测数据发送到 Azure 门户Sending telemetry to the Azure portal

默认情况下,Application Insights JavaScript SDK 会自动收集许多遥测项,这些项有助于确定应用程序和底层用户体验的运行状况。By default the Application Insights JavaScript SDK autocollects a number of telemetry items that are helpful in determining the health of your application and the underlying user experience. 这些问题包括:These include:

  • 应用中未捕获到的异常,包括以下相关信息Uncaught exceptions in your app, including information on
    • 堆栈跟踪Stack trace
    • 异常详细信息和错误随附的消息Exception details and message accompanying the error
    • 错误的行号与列号Line & column number of error
    • 引发错误的 URLURL where error was raised
  • 应用发出的网络依赖项请求XHRFETCH(默认已禁用提取集合)请求,包括以下相关信息Network Dependency Requests made by your app XHR and Fetch (fetch collection is disabled by default) requests, include information on
    • 依赖项源的 URLUrl of dependency source
    • 用于请求依赖项的命令和方法Command & Method used to request the dependency
    • 请求持续时间Duration of the request
    • 请求的结果代码和成功状态Result code and success status of the request
    • 发出请求的用户的 ID(如果有)ID (if any) of user making the request
    • 发出请求的关联上下文(如果有)Correlation context (if any) where request is made
  • 用户信息(例如位置、网络、IP)User information (for example, Location, network, IP)
  • 设备信息(例如浏览器、OS、版本、语言、分辨率、型号)Device information (for example, Browser, OS, version, language, resolution, model)
  • 会话信息Session information

遥测初始化表达式Telemetry initializers

遥测初始化表达式用于在从用户浏览器发送收集的遥测内容之前先对其进行修改。Telemetry initializers are used to modify the contents of collected telemetry before being sent from the user's browser. 它们还可用于返回 false 以阻止发送某些遥测数据。They can also be used to prevent certain telemetry from being sent, by returning false. 可将多个遥测初始化表达式添加到 Application Insights 实例,它们将按添加顺序执行。Multiple telemetry initializers can be added to your Application Insights instance, and they are executed in order of adding them.

addTelemetryInitializer 的输入参数是一个回调,该回调采用 ITelemetryItem 作为参数,并返回 booleanvoidThe input argument to addTelemetryInitializer is a callback that takes a ITelemetryItem as an argument and returns a boolean or void. 如果返回 false,则不发送遥测项,否则将继续处理下一个遥测初始化表达式(如果有),或者将遥测项发送到遥测集合终结点。If returning false, the telemetry item is not sent, else it proceeds to the next telemetry initializer, if any, or is sent to the telemetry collection endpoint.

使用遥测初始化表达式的示例:An example of using telemetry initializers:

var telemetryInitializer = (envelope) => {
  envelope.data.someField = 'This item passed through my telemetry initializer';
};
appInsights.addTelemetryInitializer(telemetryInitializer);
appInsights.trackTrace({message: 'This message will use a telemetry initializer'});

appInsights.addTelemetryInitializer(() => false); // Nothing is sent after this is executed
appInsights.trackTrace({message: 'this message will not be sent'}); // Not sent

配置Configuration

大多数配置字段的命名都可默认为 false。Most configuration fields are named such that they can be defaulted to false. instrumentationKey 以外的所有字段都是可选的。All fields are optional except for instrumentationKey.

姓名Name 默认Default 描述Description
instrumentationKeyinstrumentationKey nullnull 必需Required
从 Azure 门户获取的检测密钥。Instrumentation key that you obtained from the Azure portal.
accountIdaccountId nullnull 可选的帐户 ID(如果应用将用户分组到帐户中)。An optional account ID, if your app groups users into accounts. 不允许使用空格、逗号、分号、等于或竖线No spaces, commas, semicolons, equals, or vertical bars
sessionRenewalMssessionRenewalMs 18000001800000 如果用户处于非活动状态有这么长的时间(以毫秒为单位),则会记录会话。A session is logged if the user is inactive for this amount of time in milliseconds. 默认值为 30 分钟Default is 30 minutes
sessionExpirationMssessionExpirationMs 8640000086400000 如果会话持续了这么长的时间(以毫秒为单位),则会记录会话。A session is logged if it has continued for this amount of time in milliseconds. 默认值为 24 小时Default is 24 hours
maxBatchSizeInBytesmaxBatchSizeInBytes 1000010000 遥测批的最大大小。Max size of telemetry batch. 如果某个批超过此限制,则立即发送此批,并启动新批If a batch exceeds this limit, it is immediately sent and a new batch is started
maxBatchIntervalmaxBatchInterval 1500015000 发送前要批处理遥测数据的时间长短(毫秒)How long to batch telemetry for before sending (milliseconds)
disableExceptionTrackingdisableExceptionTracking false 如果为 true,则不自动收集异常。If true, exceptions are no autocollected. 默认值为 false。Default is false.
disableTelemetrydisableTelemetry false 如果为 true,则不收集或发送遥测数据。If true, telemetry is not collected or sent. 默认值为 false。Default is false.
enableDebugenableDebug false 如果为 true,则不管 SDK 日志记录设置如何,内部调试数据都将引发为异常,而不是记录这些数据。If true, internal debugging data is thrown as an exception instead of being logged, regardless of SDK logging settings. 默认值为 false。Default is false.
注意: 如果启用此设置,每当发生内部错误时,都会导致丢弃遥测数据。Note: Enabling this setting will result in dropped telemetry whenever an internal error occurs. 这可能有利于快速识别 SDK 的配置或用法问题。This can be useful for quickly identifying issues with your configuration or usage of the SDK. 如果你不希望在调试时丢失遥测数据,请考虑使用 consoleLoggingLeveltelemetryLoggingLevel,而不是 enableDebugIf you do not want to lose telemetry while debugging, consider using consoleLoggingLevel or telemetryLoggingLevel instead of enableDebug.
loggingLevelConsoleloggingLevelConsole 00 内部 Application Insights 错误记录到控制台。Logs internal Application Insights errors to console.
0:关闭,0: off,
1:仅限严重错误,1: Critical errors only,
2:所有内容(错误和警告)2: Everything (errors & warnings)
loggingLevelTelemetryloggingLevelTelemetry 11 内部 Application Insights 错误作为遥测数据发送。Sends internal Application Insights errors as telemetry.
0:关闭,0: off,
1:仅限严重错误,1: Critical errors only,
2:所有内容(错误和警告)2: Everything (errors & warnings)
diagnosticLogIntervaldiagnosticLogInterval 1000010000 内部日志记录队列的(内部)轮询间隔(以毫秒为单位)(internal) Polling interval (in ms) for internal logging queue
samplingPercentagesamplingPercentage 100100 要发送的事件百分比。Percentage of events that will be sent. 默认值为 100,表示发送所有事件。Default is 100, meaning all events are sent. 如果你希望避免大型应用程序达到数据上限,请设置此项。Set this if you wish to preserve your data cap for large-scale applications.
autoTrackPageVisitTimeautoTrackPageVisitTime false 如果为 true,则对于页面视图,将跟踪前一个检测的页面的查看时间并将其作为遥测数据发送,同时,为当前的页面视图启动新的计时器。If true, on a pageview, the previous instrumented page's view time is tracked and sent as telemetry and a new timer is started for the current pageview. 默认值为 false。Default is false.
disableAjaxTrackingdisableAjaxTracking false 如果为 true,则不自动收集 Ajax 调用。If true, Ajax calls are not autocollected. 默认值为 false。Default is false.
disableFetchTrackingdisableFetchTracking true 如果为 true,则不自动收集 Fetch 请求。If true, Fetch requests are not autocollected. 默认值为 trueDefault is true
overridePageViewDurationoverridePageViewDuration false 如果为 true,则在调用 trackPageView 时,trackPageView 的默认行为将更改为记录页面视图持续时间间隔的结束时间。If true, default behavior of trackPageView is changed to record end of page view duration interval when trackPageView is called. 如果为 false 且未为 trackPageView 提供自定义持续时间,则会使用导航计时 API 计算页面视图性能。If false and no custom duration is provided to trackPageView, the page view performance is calculated using the navigation timing API. 默认值为 false。Default is false.
maxAjaxCallsPerViewmaxAjaxCallsPerView 500500 默认值为 500 - 控制要为每个页面视图监视多少个 AJAX 调用。Default 500 - controls how many AJAX calls will be monitored per page view. 设置为 -1 可监视页面上的所有(无限制)AJAX 调用。Set to -1 to monitor all (unlimited) AJAX calls on the page.
disableDataLossAnalysisdisableDataLossAnalysis true 如果为 false,则对于尚未发送的项,启动时将检查内部遥测发送方缓冲区。If false, internal telemetry sender buffers will be checked at startup for items not yet sent.
disableCorrelationHeadersdisableCorrelationHeaders false 如果为 false,则 SDK 会将两个标头(“Request-Id”和“Request-Context”)添加到所有依赖项请求,以将其关联到服务器端上的对应请求。If false, the SDK will add two headers ('Request-Id' and 'Request-Context') to all dependency requests to correlate them with corresponding requests on the server side. 默认值为 false。Default is false.
correlationHeaderExcludedDomainscorrelationHeaderExcludedDomains 禁用特定域的关联标头Disable correlation headers for specific domains
correlationHeaderDomainscorrelationHeaderDomains 启用特定域的关联标头Enable correlation headers for specific domains
disableFlushOnBeforeUnloaddisableFlushOnBeforeUnload false 默认值为 false。Default false. 如果为 true,则触发 onBeforeUnload 事件时不会调用 flush 方法If true, flush method will not be called when onBeforeUnload event triggers
enableSessionStorageBufferenableSessionStorageBuffer true 默认值为 true。Default true. 如果为 true,则会将包含所有未发送的遥测数据的缓冲区存储在会话存储中。If true, the buffer with all unsent telemetry is stored in session storage. 加载页面时会还原该缓冲区The buffer is restored on page load
isCookieUseDisabledisCookieUseDisabled false 默认值为 false。Default false. 如果为 true,则 SDK 不会存储或读取 Cookie 中的任何数据。If true, the SDK will not store or read any data from cookies.
cookieDomaincookieDomain nullnull 自定义 Cookie 域。Custom cookie domain. 若要跨子域共享 Application Insights Cookie,此字段会有帮助。This is helpful if you want to share Application Insights cookies across subdomains.
isRetryDisabledisRetryDisabled false 默认值为 false。Default false. 如果为 false,则出现代码 206(部分成功)、408(超时)、429(请求过多)、500(内部服务器错误)、503(服务不可用)和 0(脱机,仅当已检测到此状态时)时会重试If false, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error), 503 (service unavailable), and 0 (offline, only if detected)
isStorageUseDisabledisStorageUseDisabled false 如果为 true,则 SDK 不会存储或读取本地和会话存储中的任何数据。If true, the SDK will not store or read any data from local and session storage. 默认值为 false。Default is false.
isBeaconApiDisabledisBeaconApiDisabled true 如果为 false,则 SDK 将使用信标 API 发送所有遥测数据If false, the SDK will send all telemetry using the Beacon API
sdkExtensionsdkExtension nullnull 设置 SDK 扩展名。Sets the sdk extension name. 仅允许使用字母字符。Only alphabetic characters are allowed. 扩展名将添加为“ai.internal.sdkVersion”标记的前缀(例如“ext_javascript:2.0.0”)。The extension name is added as a prefix to the 'ai.internal.sdkVersion' tag (for example, 'ext_javascript:2.0.0'). 默认值为 null。Default is null.
isBrowserLinkTrackingEnabledisBrowserLinkTrackingEnabled false 默认值为 false。Default is false. 如果为 true,则 SDK 将跟踪所有浏览器链接请求。If true, the SDK will track all Browser Link requests.
appIdappId nullnull appId 用于在客户端上发生的 AJAX 依赖项与服务器端请求之间进行关联。AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests. 启用信标 API 后,无法自动使用 appId,但可以在配置中手动设置它。When Beacon API is enabled, it cannot be used automatically, but can be set manually in the configuration. 默认值为 nullDefault is null
enableCorsCorrelationenableCorsCorrelation false 如果为 true,则 SDK 会将两个标头(“Request-Id”和“Request-Context”)添加到所有 CORS 请求,以将传出的 AJAX 依赖项关联到服务器端上的对应请求。If true, the SDK will add two headers ('Request-Id' and 'Request-Context') to all CORS requests to correlate outgoing AJAX dependencies with corresponding requests on the server side. 默认值为 falseDefault is false
namePrefixnamePrefix undefinedundefined 一个可选值,用作 localStorage 和 Cookie 名称的名称后缀。An optional value that will be used as name postfix for localStorage and cookie name.
enableAutoRouteTrackingenableAutoRouteTracking false 自动跟踪单页应用程序 (SPA) 中的路由更改。Automatically track route changes in Single Page Applications (SPA). 如果为 true,则每次更改路由都会将一个新的页面视图发送到 Application Insights。If true, each route change will send a new Pageview to Application Insights. 哈希路由更改 (example.com/foo#bar) 也会记录为新的页面视图。Hash route changes (example.com/foo#bar) are also recorded as new page views.

单页应用程序Single Page Applications

默认情况下,此 SDK 不会处理单页应用程序中发生的基于状态的路由更改。By default, this SDK will not handle state-based route changing that occurs in single page applications. 若要为单页应用程序启用自动路由更改跟踪,可将 enableAutoRouteTracking: true 添加到设置配置。To enable automatic route change tracking for your single page application, you can add enableAutoRouteTracking: true to your setup configuration.

目前,我们提供了一个可通过此 SDK 初始化的独立 React 插件Currently, we offer a separate React plugin which you can initialize with this SDK. 该插件也能为你实现路由更改跟踪,并可收集其他特定于 React 的遥测数据It will also accomplish route change tracking for you, as well as collect other React specific telemetry.

React 扩展React extensions

ExtensionsExtensions
ReactReact
React NativeReact Native

浏览浏览器/客户端数据Explore browser/client-side data

可以转到“指标”并添加你感兴趣的各个指标,来查看浏览器/客户端数据:Browser/client-side data can be viewed by going to Metrics and adding individual metrics you are interested in:

还可以通过门户中的“浏览器”体验查看 JavaScript SDK 中的数据。You can also view your data from the JavaScript SDK via the Browser experience in the portal.

选择“浏览器”,然后选择“失败”或“性能”。Select Browser and then choose Failures or Performance.

性能Performance

依赖项Dependencies

分析Analytics

若要查询 JavaScript SDK 收集的遥测数据,请选择“在日志(分析)中查看”按钮。To query your telemetry collected by the JavaScript SDK, select the View in Logs (Analytics) button. 如果添加 client_Type == "Browser"where 语句,则只会看到来自 JavaScript SDK 的数据,而其他 SDK 收集的任何服务器端遥测数据将被排除。By adding a where statement of client_Type == "Browser", you will only see data from the JavaScript SDK and any server-side telemetry collected by other SDKs will be excluded.

// average pageView duration by name
let timeGrain=5m;
let dataset=pageViews
// additional filters can be applied here
| where timestamp > ago(1d)
| where client_Type == "Browser" ;
// calculate average pageView duration for all pageViews
dataset
| summarize avg(duration) by bin(timestamp, timeGrain)
| extend pageView='Overall'
// render result in a chart
| render timechart

源映射支持Source Map Support

可以在 Azure 门户中取消缩小异常遥测的已缩小调用堆栈。The minified callstack of your exception telemetry can be unminified in the Azure portal. “异常详细信息”面板中的所有现有集成将适用于最近取消缩小的调用堆栈。All existing integrations on the Exception Details panel will work with the newly unminified callstack. 拖放式源映射取消缩小功能支持所有现有和将来的 JS SDK (+Node.js),因此你无需升级 SDK 版本。Drag and drop source map unminifying supports all existing and future JS SDKs (+Node.JS), so you do not need to upgrade your SDK version. 若要查看已取消缩小的调用堆栈,To view your unminified callstack,

  1. 请在 Azure 门户中选择一个异常遥测项,以查看其“端到端事务详细信息”Select an Exception Telemetry item in the Azure portal to view its "End-to-end transaction details"
  2. 确定哪些源映射对应于此调用堆栈。Identify which source maps correspond to this call stack. 源映射必须与堆栈帧的源文件相匹配,但后缀为 .mapThe source map must match a stack frame's source file, but suffixed with .map
  3. 将源映射拖放到 Azure 门户中的调用堆栈上 Drag and drop the source maps onto the call stack in the Azure portal

Application Insights Web 基本版Application Insights Web Basic

若要获得精简的体验,可以改为安装基本版 Application InsightsFor a lightweight experience, you can instead install the basic version of Application Insights

npm i --save @microsoft/applicationinsights-web-basic

此版本附带最少数量的功能,你可以根据自己的需求对其进行构建。This version comes with the bare minimum number of features and functionalities and relies on you to build it up as you see fit. 例如,它不执行自动收集(未捕获的异常、AJAX 等等)。For example, it performs no autocollection (uncaught exceptions, AJAX, etc.). 此版本不包含用于发送某些遥测类型的 API(例如 trackTracetrackException 等),因此你需要提供自己的包装器。The APIs to send certain telemetry types, like trackTrace, trackException, etc., are not included in this version, so you will need to provide your own wrapper. 提供的唯一 API 是 trackThe only API that is available is track. 此处提供了一个示例。A sample is located here.

示例Examples

有关可运行的示例,请参阅 Application Insights Javascript SDK 示例For runnable examples, see Application Insights Javascript SDK Samples

从旧版 Application Insights 升级Upgrading from the old Version of Application Insights

SDK V2 版本中的重大更改:Breaking changes in the SDK V2 version:

  • 为了让用户生成更好的 API 签名,某些 API 调用(例如 trackPageView、trackException)已更新。To allow for better API signatures, some of the API calls such as trackPageView, trackException have been updated. 不支持在 IE8 或更低版本的浏览器中运行。Running in IE8 or lower versions of the browser is not supported.
  • 由于数据架构更新,遥测信封的字段名称和结构已更改。Telemetry envelope has field name and structure changes due to data schema updates.
  • 已将 context.operation 转移到 context.telemetryTraceMoved context.operation to context.telemetryTrace. 此外还更改了一些字段 (operation.id --> telemetryTrace.traceID)Some fields were also changed (operation.id --> telemetryTrace.traceID)
    • 若要手动刷新当前页面视图 ID(例如,在 SPA 应用中),可以使用 appInsights.properties.context.telemetryTrace.traceID = Util.newId() 执行此操作If you want to manually refresh the current pageview ID (for example, in SPA apps) this can be done with appInsights.properties.context.telemetryTrace.traceID = Util.newId()

如果你正在使用最新的 Application Insights PRODUCTION SDK (1.0.20),并想要查看新 SDK 是否可在运行时中正常工作,请根据当前的 SDK 加载方案更新 URL。If you're using the current application insights PRODUCTION SDK (1.0.20) and want to see if the new SDK works in runtime, update the URL depending on your current SDK loading scenario.

  • 通过 CDN 方案下载:更新当前用于指向以下 URL 的代码片段:Download via CDN scenario: Update the code snippet that you currently use to point to the following URL:

    "https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js"
    
  • NPM 方案调用 downloadAndSetup 以从 CDN 下载完整的 ApplicationInsights 脚本,并使用检测密钥将其初始化:NPM scenario: Call downloadAndSetup to download the full ApplicationInsights script from CDN and initialize it with instrumentation key:

    appInsights.downloadAndSetup({
       instrumentationKey: "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx",
       url: "https://az416426.vo.msecnd.net/scripts/b/ai.2.min.js"
       });
    

在内部环境中进行测试,以验证是否可按预期方式监视遥测。Test in internal environment to verify monitoring telemetry is working as expected. 如果一切正常,请相应地将 API 签名更新为 SDK V2 版本,并部署到生产环境中。If all works, update your API signatures appropriately to SDK V2 version and deploy in your production environments.

SDK 性能/开销SDK performance/overhead

经过 gzip 压缩后只有 25 KB,只需大约 15 毫秒即可完成初始化,Application Insights 在网站中的加载时间可忽略不计。At just 25 KB gzipped, and taking only ~15 ms to initialize, Application Insights adds a negligible amount of loadtime to your website. 使用代码片段时,很快就能加载极少量的库组件。By using the snippet, minimal components of the library are quickly loaded. 同时,整个脚本将在后台下载。In the meantime, the full script is downloaded in the background.

从 CDN 下载脚本时,页面的所有跟踪将会排队。While the script is downloading from the CDN, all tracking of your page is queued. 在下载的脚本以异步方式完成初始化后,将会跟踪已排队的所有事件。Once the downloaded script finishes asynchronously initializing, all events that were queued are tracked. 因此,在页面的整个生命周期内,你都不会丢失任何遥测数据。As a result, you will not lose any telemetry during the entire life cycle of your page. 此设置过程可为页面提供一个无缝分析系统,而用户察觉不到该系统。This setup process provides your page with a seamless analytics system, invisible to your users.

摘要:Summary:

  • 经过 gzip 压缩后为 25 KB25 KB gzipped
  • 总初始化时间为 15 毫秒15 ms overall initialization time
  • 在页面的整个生命周期内都不会失去跟踪Zero tracking missed during life cycle of page

浏览器支持Browser support

Chrome Firefox IE Opera Safari
最新 ✔Latest ✔ 最新 ✔Latest ✔ 9+ ✔9+ ✔ 最新 ✔Latest ✔ 最新 ✔Latest ✔

开源 SDKOpen-source SDK

Application Insights JavaScript SDK 是开源的,用户可查看其源代码;若要对该项目做贡献,请访问官方 GitHub 存储库The Application Insights JavaScript SDK is open-source to view the source code or to contribute to the project visit the official GitHub repository.

后续步骤Next steps