How to set script src path dynamically using Angular.js and Javascript - javascript

I need one help.I need to set js/css path name dynamically uaing Angular.js/Javascript/Jquery.I am explaining my code below.
<script src="/crm/controller/productController.js" type="text/javascript"></script>
Suppose i have the above script tag.Here my path is
/crm/controller/productController.js.I need to set /crm/ in my config file and i will set this path name in every script tag.In php it is happening like below.
define("USER_SITE_URL", "http://www.absclasses.com/");
<script type="text/javascript" src="<?php echo SITE_URL;?>js/jquery-1.9.1.min.js"></script>
As i am not using PHP. How it can me made using Angular.js or Javascript/Jquery.

You can use HTML base tag as follows.
<base href="http://www.absclasses.com/" />
If you want to do this with angular config block, you can use the following javascript code also with some modification.
document.write("<base href='http://" + document.location.host + "' />");
You can also define store document.location.host to a variable and use that.

In the javascript, you can set global variable.
function globalSource() {
jqueryUrl = "http://xxxxxxx",
angularUrl = "http://xxxxxx"
}
when you want to use.
(function() {
globalSource();
//Get your dom and change attributes src link
//ex: var xx = document.getElementsByTagName('script')[0].setAttribute("src", window.jqueryUrl );
})();

<xsl:variable name="Path" select="/crm/controller/"></xsl:variable> <!-- Global path variable. -->
<xsl:variable name="myScriptPath" select="concat($Path, 'productController.js')"></xsl:variable> <!-- Relative script path variable. -->
<script src="{$myScriptPath}"/> <!-- Attach script. -->

Related

How do I reference a javascript variable from a razor section?

I'm trying to dynamically render a CSS file to my view, but part of the location of the file is in a javascript variable.
Currently I have:
#section Styles {
#{
<link href="#Url.Content(Model.CssPath)" rel="stylesheet" type="text/css" />
}
}
But I need to include the variable in the path, like this:
#section Styles {
#{
var pathPrefix = "somePath/";
<link href="#Url.Content(pathPrefix + Model.CssPath)" rel="stylesheet" type="text/css" />
}
}
I understand the server-side code is evaluated before the javascript variable exists, so how else do I accomplish this?
First of all - why mixing client-side/server-side code?
You cannot use JS variable along with server-side generated content because - as you said - it is executed on server before client's browsers hits JS code. This is expected behavior.
If this variable value can be determined on the server-side, you should move it there.
If it has to be generated on the client side, you can generate <link> tag using document.createElement('link'); but it seems odd to me :)
Rather than trying to add the stylesheet via the razor view I would put the csspath into a javascript variable and then use jquery to combine it with the pathPrefix and append the stylesheet that way.
something like....
<script>
var cssPath = #Model.cssPath;
var pathPrefix = "www.";
$('head').append('<link rel="stylesheet" type="text/css" href="'+pathPrefix+cssPath+'">');
</script>

How to change add javascript files dynamically in the header of an html file?

I have an html page, I need to add some reference to JS files in the head of the html.
The following code is working, but the scriptTVKeyValue is always being added before the tag
I would like to add instead directly after
Any idea what I am doing wrong here?
<head>
// I want reference added here
<script src="js/jquery.js"></script>
<script src="js/json2.js"></script>
// Reference to file added here
</head>
// APP_MAIN.onLoad()
var scriptTVKeyValue = document.createElement('script');
scriptTVKeyValue.type = 'text/javascript';
scriptTVKeyValue.src = '$MANAGER_WIDGET/Common/API/TVKeyValue.js';
head.appendChild(scriptTVKeyValue);
Look at http://www.jspatterns.com/the-ridiculous-case-of-adding-a-script-element/
You should have the answer
Solution using jQuery:
//Take the refference to the previous node
var $jsFile = $container.find('[src="js/jquery.js"]');
var fileName= '$MANAGER_WIDGET/Common/API/TVKeyValue.js';
// Insert the script
$jsFile .insertAfter($('<script>')
.attr('type', 'text/javascript')
.attr('src', fileName));
If you are happy/allowed to use a JS library, then you can load the scripts with requireJS It has advanced features to do this: it will enable you to call functions after your dynamically added script is loaded.

How do I set the src address dynamically?

I am trying to grab information from the page url to set the src for a data file.
So, say page url is: page.html?x=data_file_3
(The ideas is I could change the url to access other data files: data_file_4, etc.)
I grab the "data_file_3" part of the url and put it in a variable:
(the code I use for this works fine -- so result is)
folder = "/data_file_3/content.js" -- the content of this file is just an array
Then I try this:
<script id="url" type="text/javascript"></script>
<script language="javascript">
...
var u = document.getElementById('url');
u.src = folder;
...
</script>
But this doesn't work (the array data does not show up on the page). I put this code right where I used to hard code:
<script type="text/javascript" src="/data_file_3/content.js"></script>
The hard-coded version works. Any ideas about how I can do this?
Sounds like you are trying to create script tags dynamically.
var scr = document.createElement('script');
scr.src = 'script_path';
document.getElementsByTagName('head')[0].appendChild(scr);
You can wrap this in a function where 'script_path' is whatever you're path you're passing in.
Note also that 'text/javascript' is not required. All browsers understand that its javascript.

Accesing variables declared in JAVASCRIPT in a different HTML FILE

I have two files screen.html and db_fun.js.I have declared a variable at just the beginning as follows:
db_fun.js
var name = "abc";
now i tried to access this variable in the screen.html file as follows
screen.html
<html>
<body>
<form name = "screen" action = "db_fun.js">
<p> <script>document.write(name);</script> </p>
</form>
</body>
<script src="db_fun.js" type="text/javascript" />
</html>
it doesn't print nethn. Y so?
add this to the head
<script type="text/javascript" src="db_fun.js"></script>
I think that you should move
<script src="db_fun.js" type="text/javascript" />
In the head of the page. I.e. before document.write.
Because in the moment where you are trying to print 'name', the variable is still not created. Also I think that it is not a very good practice to use document.write to add content to your page. Try using jQuery or some other library. For example:
$(document).ready(function() {
$("p").html(name);
});
That's because you are inserting your JavaScript in the page footer. You have to firstly load your javascript file into your web site (in the head section for example) and then use your variable.

Relative Paths in Javascript in an external file

So I'm running this javascript, and everything works fine, except the paths to the background image. It works on my local ASP.NET Dev environment, but it does NOT work when deployed to a server in a virtual directory.
This is in an external .js file, folder structure is
Site/Content/style.css
Site/Scripts/myjsfile.js
Site/Images/filters_expand.jpg
Site/Images/filters_colapse.jpg
then this is where the js file is included from
Site/Views/ProductList/Index.aspx
$("#toggle").click(function() {
if (left.width() > 0) {
AnimateNav(left, right, 0);
$(this).css("background", "url('../Images/filters_expand.jpg')");
}
else {
AnimateNav(left, right, 170);
$(this).css("background", "url('../Images/filters_collapse.jpg')");
}
});
I've tried using '/Images/filters_collapse.jpg' and that doesn't work either; however, it seems to work on the server if I use '../../Images/filters_collapse.jpg'.
Basically, I want have the same functionallity as the ASP.NET tilda -- ~.
update
Are paths in external .js files relative to the Page they are included in, or the actual location of the .js file?
JavaScript file paths
When in script, paths are relative to displayed page
to make things easier you can print out a simple js declaration like this and using this variable all across your scripts:
Solution, which was employed on StackOverflow around Feb 2010:
<script type="text/javascript">
var imagePath = 'http://sstatic.net/so/img/';
</script>
If you were visiting this page around 2010 you could just have a look at StackOverflow's html source, you could find this badass one-liner [formatted to 3 lines :) ] in the <head /> section
get the location of your javascript file during run time using jQuery by parsing the DOM for the 'src' attribute that referred it:
var jsFileLocation = $('script[src*=example]').attr('src'); // the js file path
jsFileLocation = jsFileLocation.replace('example.js', ''); // the js folder path
(assuming your javascript file is named 'example.js')
A proper solution is using a css class instead of writing src in js file.
For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Good question.
When in a CSS file, URLs will be relative to the CSS file.
When writing properties using JavaScript, URLs should always be relative to the page (the main resource requested).
There is no tilde functionality built-in in JS that I know of. The usual way would be to define a JavaScript variable specifying the base path:
<script type="text/javascript">
directory_root = "http://www.example.com/resources";
</script>
and to reference that root whenever you assign URLs dynamically.
For the MVC4 app I am working on, I put a script element in _Layout.cshtml and created a global variable for the path required, like so:
<body>
<script>
var templatesPath = "#Url.Content("~/Templates/")";
</script>
<div class="page">
<div id="header">
<span id="title">
</span>
</div>
<div id="main">
#RenderBody()
</div>
<div id="footer">
<span></span>
</div>
</div>
I used pekka's pattern.
I think yet another pattern.
<script src="<% = Url.Content("~/Site/Scripts/myjsfile.js") %>?root=<% = Page.ResolveUrl("~/Site/images") %>">
and parsed querystring in myjsfile.js.
Plugins | jQuery Plugins
Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript
<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
You need to add runat="server" and and to assign an ID for it, then specify the absolute path like this:
<script type="text/javascript" runat="server" id="myID" src="~/js/jquery.jqGrid.js"></script>]
From the codebehind, you can change the src programatically using the ID.
This works well in ASP.NET webforms.
Change the script to
<img src="' + imagePath + 'chevron-large-right-grey.gif" alt="'.....
I have a master page for each directory level and this is in the Page_Init event
Dim vPath As String = ResolveUrl("~/Images/")
Dim SB As New StringBuilder
SB.Append("var imagePath = '" & vPath & "'; ")
ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "LoadImagePath", SB.ToString, True)
Now regardless of whether the application is run locally or deployed you get the correct full path
http://localhost:57387/Images/chevron-large-left-blue.png

Categories