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
- public class ConfigurationController : ApiController
- {
- [HttpGet]
- public string LoadSettings(Domain.Entities.Configuration model)
- {
- string value = ConfigurationManager.AppSettings.Get(model.Key);
- return value;
- }
- }
Step 2:
Create a javascript function which will load javascript or css paths dynamically.
- function loadjscssfile(filename, filetype) {
- if (filetype == "js") { //if filename is a external JavaScript file
- var fileref = document.createElement('script');
- fileref.setAttribute("type", "text/javascript");
- fileref.setAttribute("src", filename);
- }
- else if (filetype == "css") { //if filename is an external CSS file
- var fileref = document.createElement("link");
- fileref.setAttribute("rel", "stylesheet");
- fileref.setAttribute("type", "text/css");
- fileref.setAttribute("href", filename);
- }
- if (typeof fileref != "undefined")
- document.getElementsByTagName("head")[0].appendChild(fileref);
- }
Step 3:
Create javascript function to call that Api method and call that function on page load.
- function loadFiles() {
- debugger;
- var configuration = {
- Key: "IdentityProviderScriptPath"
- };
- $.ajax({
- url: "../Api/Configuration/LoadSettings" + productName,
- //data: { name: productName },
- type: "GET",
- dataType: "jsonp",
- error: function (request, status, error) {
- alert(request.responseText);
- },
- success: function (path) {
- loadjscssfile(path, "js");
- }
- });
- }
- <body onload="loadScriptFiles();">
Happy Coding
Comments
Post a Comment