Summary of methods for referencing CDN content

Source: Internet
Author: User
Tags string back html5 boilerplate

1.1.1 Summary

I believe everyone has heard of CDN and even used related technologies. Maybe some people will answer "I have never heard of or used this technology". Is that true?

CDN stands for Content Delivery Network (CDN. The purpose is to add a new network architecture to the existing Internet to publish website content to the "edge" closest to the user's network, so that users can obtain the desired content nearby, solve the problem of Internet congestion and improve the response speed of users accessing websites.

After reading the above definition, we can simply describe CDN as: Content Delivery, solving network congestion and providing website speed.

In fact, CDN is not mysterious and even we often use this technology during daily development, for example, referencing network script libraries (such as jQuery) and network image resources.

We often find that many websites reference the corresponding Javascript library from Google's CDN, but many websites do not consider the failure of loading CDN content. We do not mean that Google's CDN is very fragile, it's just not afraid to be afraid of 10 thousand.

In the following blog, we will introduce how to prevent loading of CDN content.

  • Basic Method
  • Solution in HTML5 Boilerplate
  • Javascript Loader
  • ASP. NET Web Form 4.5
  • AspNet. ScriptManager. jQuery package
  • ASP. NET Web Optimization package
1.1.2 basic methods of Text

To check whether the CDN content is successfully loaded, we can add code after the script code to determine whether the type or variable exists. If the script code is not stored, it indicates that the CDN loading fails, then our program should load the local script. Next we will load the jQuery library as an example. The specific implementation is as follows:

<!-- Adds google cdn reference --><script src=>(jQuery == ) {        document.write(unescape());    }

Above, we reference the jQuery library of Google CDN, And then we add an if statement after the script code to determine whether the jQuery library is successfully loaded, if the file is not loaded successfully, we dynamically load the local jQuery library.

Here, we directly use URL encoding in the document. write method, encode "<" as "% 3C", and then use the unescape () method to restore the string.

, We use the unescape () method to convert the string back. We can see that the output is a normal Script Reference code.

Now, we have a question: "Why do we use character encoding instead of regular characters ?", In fact, there is a reason, which means that our code can run normally in XML, XHTML, or HTML without including the code in CDATA (For details, refer to here ).

Solution in HTML5 Boilerplate

Next, we will introduce how to use the reference address of "protocol omitted" and how to simplify local code loading. Before that, let's first understand the advantages of using the reference address of "protocol omitted.

We know that using a safe reference address is understandable to ensure information security. However, excessive use of static SSL Cache resources, such as the jQuery library, may also result in lower loading performance; for the same reason, the browser needs to encrypt these resources, and most browsers do not cache files obtained through SSL by default.

Worse, even if the user already has a local cached copy on the disk, but the jQuery file is obtained from Google CDN through an HTTP request, it cannot be used by different protocols of the same request for HTTPS, that is, two cached files must be saved for different protocols in the same request.

URL of the Http request:


The URL of the Https request is as follows:


When Google CDN's jQuery library is referenced through Https on the regular Http page, the cache performance will decrease. We should try to avoid referencing unnecessary Https content on the Http page.

In RFC3986, section 4.2 stipulates that the Protocol (Http or Http) is still valid if the protocol of a URL is omitted. When the protocol of a URL is omitted, the browser uses the protocol of the basic document, in this way, we can flexibly specify the URL address. Therefore, we can reference the jQuery library in the following ways.

<!-- Adds protocol-less google cdn reference --><script src=>

The above code looks strange, but the URL with "omitted protocol" is the best way to reference third-party content, which can be referenced through Http or Https.

When a page is loaded, the unencrypted request script is referenced and cached in Http mode, and the encrypted request script uses Https reference content according to the "protocol omitted" method, therefore, the URL of "protocol omitted" allows a single script to reference content more flexibly.

Next, we will continue to simplify the code for loading local scripts. When jQuery is successfully loaded to the page, it will create a global jQuery variable. We can use the jQuery attribute of window (window. jQuery) to access the value of this variable. If jQuery is not loaded successfully, then window. jQuery is undefined.

Therefore, we can simplify the Code as follows:

<!-- Adds protocol-less google cdn reference --><script src=>window.jQuery || document.write()

We used the "|" operator to determine the window. whether jQuery is of an undefined type, if window. jQuery does not define how to execute the following code to load the local jQuery script. HTML5 Boilerplate uses the above method to handle CDN content loading failure.

Javascript Loader

Some people use JavaScript loaders such as yepnope, which is a js script that can selectively load resource files asynchronously Based on Input conditions. It can load only the js or css required by users on the page, the following describes how to use yepnope by loading jQuery. The specific implementation is as follows:

yepnope([{    load: ,    complete: () {        (!window.jQuery) {            yepnope();        }    }}]);

Above, we use the loader yepnope to load jQuery into the page. Next, we will introduce how to load jQuery using RequireJS. The specific implementation is as follows:

requirejs.config({    enforceDefine: ,    paths: {        jquery: [            ,            ]    }});([], ($) {    });

We can use the URL address omitted by the Protocol in the RequireJS loader, so that we can avoid the encryption and cache problems mentioned above.

Although the JS loader can also solve the problem of CDN content loading failure, it is unnecessary to introduce yepnope or RequireJS to prevent CDN content loading failure.

ASP. NET Web Form 4.5

For each ASP. NET Web form developer, we need to understand the new features added in ASP. NET 4.5, which include the features of loading local content when processing CDN content loading fails.

First, add the ScriptManager control on the page, set the EnableCdn attribute of the control to "True", and then add the name of the content to be loaded. The following uses loading jQuery as an example:

"" """" 

Above, we use the ScriptManager control to specify the jQuery library to be loaded, but here we have a question: we did not specify the URL address for loading the jQuery library, and second, after loading fails, the local jQuery library path is not specified.

Now, we can run the Page code to view the script code generated by ScriptManager. The specific code is as follows:

<script src=type=>(window.jQuery) || document.write(); 

Through the above Code, we found that the URL of the jQuery library loaded by ScriptManager by default is.

Although this method is simple and worry-free, it loads content to Microsoft CDN by default. What if we want to use Google CDN? Is Microsoft planning to monopolize CDN? In addition, how should we load the jQuery 2.0.0 library?

In fact, we can use the custom ScriptResourceMapping method to specify the loaded CDN and jQuery libraries. We need to add the following code to the Global. asax file:

mapping = .ScriptResourceMapping;mapping.AddDefinition(, ScriptResourceDefinition{    Path = ,    DebugPath = ,    CdnPath = ,    CdnDebugPath = ,    CdnSupportsSecureConnection = ,    LoadSuccessExpression = });

Above, we have defined loading Google CDN and jQuery 2.0.0. Next we will re-run the Page code to check whether the script code generated by ScriptManager corresponds to our settings.

<script src=type=>(window.jQuery) || document.write(); 

Now we can see that Google CDN is used and jQuery 2.0.0 is loaded.

AspNet. ScriptManager. jQuery package

In ASP. in NET4.5, if we want to use jQuery 2.0.0 or an updated version, we can use AspNet. scriptManager. the jQuery package is used to manage the update of the Reference Library. It also includes the CDN information configuration function. To obtain the latest update, choose tools> extended Tool Manager> AspNet. scriptManager. jQuery, and then update the package to obtain the latest jQuery library.

ASP. NET Web Optimization package

If we are using the ASP. net mvc program, we can also manage CDN configuration information by updating the ASP. NET Web Optimization package.

Next, specify the URL of our CdnPath in BundleConfig and open App_Start \ BundleConfig. cs, we can see that there is a RegisterBundles () method in it. below is part of the code of the RegisterBundles () method:

RegisterBundles(BundleCollection bundles){    bundles.UseCdn = ;    BundleTable.EnableOptimizations = ; jquery = ScriptBundle(, ).Include(            );    jquery.CdnFallbackExpression = ;    bundles.Add(jquery);    }
1.1.3 Summary

In this article, we will introduce some processing mechanisms for CDN content reference failure. In terms of processing methods, I think the HTML5 Boilerplate solution is not only concise, but also does not need to introduce third-party libraries.

At the same time, we also introduced the advantages of using CDN with "protocol omitted", but we should pay attention to one thing, if we run a URL that uses "protocol omitted" locally, it may not work as expected. Because the basic protocol used for "protocol omitted" on the local running page is file, instead of http or https, we generally cannot get the CDN content by running the page locally. We can place the page to the Local Web server for running, such as Apache or IIS, then run the http: // localhost address to load it successfully.

  • Http://
  • Http://
  • Https://

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.