简体   繁体   中英

ASP.NET MVC routing - loading .js scrips dynamically

Trying to load JavaScript plugin scripts on a _Layout.cshtml page dynamically - from inside a JavaScript file (its from a Bootstrap template). I have changed the PLUGINS_PATH in the script as follows:

// Declared at top of script
var PLUGINS_PATH = './Content/plugins/';

// ... for each plugin script - e.g
jQuery().themeLoadPlugin(["jPanelMenu/jquery.jpanelmenu.min.js", "jRespond/js/jRespond.js"], [], initjPMenu);

 // Load plugin
 // --------------------------------
 themeLoadPlugin: function(js, css, callback, placement) {
 jQuery.ajaxPrefilter( "script", function( s ) {
     s.crossDomain = true;
 });
 if (js) {
  var progress = 0;
  var internalCallback = function () {
    // Complete
    if (++progress === js.length) {
      $.each(css, function(index, value) {
        jQuery('head').prepend('<link href="' + PLUGINS_PATH + value + '" rel="stylesheet" type="text/css" />');
      });

      if (callback && typeof(callback) === "function") {
        callback();
      }
    }
  };

  if (placement === undefined) {
    $.each(js, function(index, value) {
      $.getScript(PLUGINS_PATH + value, internalCallback);
    });
  }
  else if (placement === 'append') {
    $.each(js, function(index, value) {
      jQuery('script[src*="bootstrap.min.js"]').after('<script src="' + PLUGINS_PATH + value + '"></script>');
      internalCallback();
    });
  }
 }
}

The above works for the index page - eg root of application - http://localhost:1234/ - but if I then if I browse to another page then the links obviously break as the are looking for - eg on the Contact page : http://localhost:1234/Home/Content/plugins/jPanelMenu/jquery.jpanelmenu.min.js

If I change the plugins path to : PLUGINS_PATH = '~/Content/plugins/'; then they break on every page with the following:

 http://localhost:1234/~/Content/plugins/jPanelMenu/jquery.jpanelmenu.min.js 

Hope I have explained the issue adequately, any help appreciated.

The tilde (~) doesn't work in the src attribute of a script tag, you'll just get a literal ~ in the path as you have found. Try:

PLUGINS_PATH = '/Content/plugins/'

Using a single dot as you did originally makes the path relative to the current directory, which again as you have found will change as you navigate around. When setting the script source:

/ relative to the root

./ relative to the directory that contains the current file

../ relative to the parent directory of the current directory

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM