3

I have a requirement of including a .js file (more jQuery code) at a run time in a currently working jQuery script. For example, if my page gets authenticated, then I want to include a particular script file. I want to do this in ASP.Net MVC.

Is there a way to do this? If so, what path do I give when calling that file?

I googled $.getScript('file_path'); but my page is getting refreshed in a loop, I don't why! Maybe I'm doing something wrong in path.

Any help would be much appreciated! Thank you.

7
  • have a look at require js. requirejs.org Commented Jul 18, 2017 at 7:32
  • $.getScript() is exactly what you need. We can't help you with the refreshing problem without seeing your code, though. Commented Jul 18, 2017 at 7:37
  • @RoryMcCrossan Can you help me with the path which I should provide in it. Like, I've my js file in "Scripts" folder in solution explorer, say content.js, and I want to call it in $.getScript();, what path should I give? like - "~/Scripts/content.js" or something else? Commented Jul 18, 2017 at 7:40
  • 1
    You can't use ~ in a JS code directly, as it's a MVC construct. You need to use a relative path, eg $.getScript('/basefolder/foo.js'); Commented Jul 18, 2017 at 7:43
  • @RoryMcCrossan I've tried the above thing as below : xhr.onreadystatechange = function (e) { if (xhr.readyState === 4 && xhr.status == 200) { $.getScript(xhr.responseText); } else if (xhr.readyState === 4 && xhr.status == 403) { location.href = '/Home/Auth'; } }; while "xhr.responseText" would reply as "/Scripts/content.js" but no success, I think path is being a issue. Commented Jul 18, 2017 at 8:01

4 Answers 4

0

Try this Including a .js file within a .js file

Basically, create script tag, append it so that it is read before the one that requires it & load the needed .js

Sign up to request clarification or add additional context in comments.

Comments

0
//Load JS files as following ["../common/howler.min.js","js/min.js"].forEach(function (src) { var script = document.createElement('script'); script.src = src; script.async = false; document.head.appendChild(script); }); 

Comments

0

$.getScript() is exactly what you should use for this.

I want to call it in $.getScript();, what path should I give? like - "~/Scripts/content.js" or something else?

The issue there is because the tilde character (~) is an ASP.Net MVC construct which will not work in Javascript. For JS you need to use a relative path, for example:

$.getScript('/basefolder/foo.js'); 

Comments

0

Added correct path and it worked with "$.getScript();"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.