Donate

Script Selector With Specified Attribute Not Found When Using jQuery In ASP.NET MVC

I have this script below that will insert a dynamically defined script tag next to an existing script element in an ASP.NET MVC page.
$(document).ready(function () {
 script.type = "text/javascript";
 script.src = '/Scripts/bootstrap3.2.0.js';
 $(script).insertAfter('script[src*="bootstrap.js"]');
 $('script[src*="bootstrap.js"]').attr('src', '');
});
Using the script above, I wasn't able to achieve the output since it can't locate the particular script tag. Upon investigating the production site, it appears that the scripts are bundled and the code above has no effect. With slight modification of the code to check if a script is bundled, I managed to get the inserting of script working.
$(document).ready(function () {

 var script = document.createElement('script');
 script.type = "text/javascript";
 script.src = '@Url.Content("~/Scripts/bootstrap3.2.0.js")';
 
 //Check if script tag exists with specific attribute
 if ($('script[src*="bootstrap.js"]').attr('src') === undefined) {
  //scripts are bundled in MVC
  $(script).insertAfter('script[src*="/bundles/bootstrap?v"]');               
 }
 else {
  $(script).insertAfter('script[src*="bootstrap.js"]');
  $('script[src*="bootstrap.js"]').attr('src', '');
 }
});


Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input