Wednesday, March 12, 2014

Dynamically Load External JS , CSS file paths in webconfig

 

If you want to load JavaScript paths or CSS paths saved in web config app settings you can use the following solution.

Step 1:

Create a API controller method which will return the appsettings

  1. public class ConfigurationController : ApiController
  2.  {
  3.   
  4.      [HttpGet]
  5.       public string LoadSettings(Domain.Entities.Configuration model)
  6.  {
  7.      string value = ConfigurationManager.AppSettings.Get(model.Key);
  8.      return value;
  9.  }
  10.  }

 

Step 2:

Create a javascript function which will load javascript or css paths dynamically.

  1. function loadjscssfile(filename, filetype) {
  2.       if (filetype == "js") { //if filename is a external JavaScript file
  3.           var fileref = document.createElement('script');
  4.           fileref.setAttribute("type", "text/javascript");
  5.           fileref.setAttribute("src", filename);
  6.       }
  7.       else if (filetype == "css") { //if filename is an external CSS file
  8.           var fileref = document.createElement("link");
  9.           fileref.setAttribute("rel", "stylesheet");
  10.           fileref.setAttribute("type", "text/css");
  11.           fileref.setAttribute("href", filename);
  12.       }
  13.       if (typeof fileref != "undefined")
  14.           document.getElementsByTagName("head")[0].appendChild(fileref);
  15.   }

 

Step 3:

Create javascript function to call that Api method and call that function on page load.

  1. function loadFiles() {
  2.     debugger;
  3.     var configuration = {
  4.         Key: "IdentityProviderScriptPath"
  5.  
  6.     };
  7.  
  8.  
  9.     $.ajax({
  10.  
  11.         url: "../Api/Configuration/LoadSettings" + productName,
  12.         //data: { name: productName },
  13.         type: "GET",
  14.         dataType: "jsonp",
  15.         error: function (request, status, error) {
  16.             alert(request.responseText);
  17.         },
  18.         success: function (path) {
  19.             loadjscssfile(path, "js");
  20.         }
  21.     });
  22.  
  23.     
  24.  
  25. }

 

  1. <body onload="loadScriptFiles();">

Happy Coding

No comments :

Post a Comment