JAVA SCRIPT - Serving Code from a CDN - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript JAVA SCRIPT - Serving Code from a CDN - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Wednesday, January 2, 2019

JAVA SCRIPT - Serving Code from a CDN

Serving Code from a CDN


Problem

You’ve created a module or library and want to make it available for others to use. You’re providing it for download, but you also want to provide a link to the code allowing people to directly link it—a concept known as hotlinking. However, you don’t want to host the source on your own server because you’re concerned about up-time, availability, and performance. 

Solution

Use a content delivery network (CDN)—sometimes referred to as a content distribution network—to host your module/library. In addition, encourage developers to link to the module/library using a protocol-less URL or protocol-relative URL, in order to prevent unnecessary browser or user agent warnings:

//somedomain.com/somescript.js


EXPLAIN

The first time you access a web page or application that incorporates a JavaScript file, the browser or other user agent typically caches the results. The browser pulls up the cached library the next time you access the file, making the access that much faster. 

The ability to take advantage of browser caching is just one of the reasons why hosting popular JavaScript libraries on a CDN makes sense. Others are ensuring access even if your server goes down (or goes away), as well as preventing an unnecessary burden on your own server. 

After all, when you provide a link to a JavaScript file to download, people will link the script directly (as the jQuery folks discovered). There are various CDNs, and which one you use is dependent on cost, availability, and company preference. 

Google provides CDN service for popular script libraries, but hosting libraries is by invitation only. jQuery uses MaxCDN, but it is a commercial service. In fact, most CDNs are commercial, with only a few, such as cdnjs, providing a free service.

Once you do decide on a CDN, when you provide links for developers, you’ll also want to encourage the use of protocol-less or a protocol-relative URL:

//somedomain.com/library.js

This is because the browser or user agent will use the same protocol used to access the web page with all the protocol-less links, which means the resource is accessed with a compatible protocol. If you’ve ever accessed a script or file with “http://” in a web page that you’ve accessed with, “https://”, then you’re familiar with the annoying warning you can get in a browser such as Internet Explorer.

No comments:

Post a Comment

Post Top Ad