asp.net.ph

Skip Navigation Links

Miscellaneous JavaScript Examples

Abakada ~ Back to Basics


Linking to Browser-specific Stylesheets

This example shows how to detect a user’s browser and link the current document to a corresponding style sheet.

This is implemented in two parts: the main script which is a separate .js file, and a calling script written within the HEAD of each page that will link to the style sheets.

STEP 1: Copy this code as is and save it as a separate file as css.js

<!--
if ( navigator.userAgent.indexOf ( "Edg" ) > -1 )
   document.write ( '<link rel="stylesheet" type="text/css" href="/shared/edge.css">' )
else if ( navigator.userAgent.indexOf ( "Chrome" ) > -1 )
   document.write ( '<link rel="stylesheet" type="text/css" href="/shared/chrom.css">' )
else if ( navigator.userAgent.indexOf ( "Firefox" ) > -1 )
   document.write ( '<link rel="stylesheet" type="text/css" href="/shared/moz.css">' )
else document.write ( '<link rel="stylesheet" type="text/css" href="/shared/def.css">' )
//-->

Note that the above example assumes that you have three style sheets: one for Microsoft® Edge®, one for Google Chrome®, and one for Mozilla Firefox®, and one for others.

Make sure that each <link href= ... > in the script points to the proper path and filename of your style sheets. If you are not sure, see the Introduction to URIs in Web Authoring Basics.

STEP 2: Copy this code into the HEAD of each HTML document that you intend to link to the stylesheets.

<script language="JavaScript" src="css.js"></script>

If you change the name and/or location of the main .js file in Step 1, make sure that the <script src= ... > in Step 2 above references the correct path and filename of the .js file, or the script will not be called and thus not function as intended.


Back to top


© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note