简体   繁体   中英

Pass variable to JS file

Although this question have been asked and answered before, including on this website, I am not managing to solve my problem.

I am using Masterpages, and Javascript files... and everyone now how "tricky" masterpages get with relative paths...

Well, I am using a png fix called: unit Png Fix (quite good to be honest... even better than the JQuery one), and this fix needs to use a small image called clear.gif. The path to the clear.gif file is being stored inside a variable that is in the JavaScript file.

However, and since I am using Masterpages I cannot simply open the JS File and write a static path... has i thought.

What I tried was: remove the variable from the JS File, and declare it outside, but in the sabe Script block. Like this:

 <!--[if lt IE 7]>
        <script src="<%= ResolveClientUrl("~/masterpages/js/unitpngfix.js") %>" type="text/javascript">
            var clear="<%= ResolveClientUrl("~/masterpages/img/clear.gif") %>";
        </script>
<![endif]-->

I even tried to declare it in the Head of the website. (I'm placing my JS files at the bottom of my page, to speed it up).

Unfortunately my solutions didn't work... which is why i am doing this question here. :(

You can't declare a src and content in a single element.

from the script element definition on the W3C site :

If the src has a URI value, user agents must ignore the element's contents and retrieve the script via the URI

Try separating them:

<script type="text/javascript">
    var clear="<%= ResolveClientUrl("~/masterpages/img/clear.gif") %>";
</script>
<script src="<%= ResolveClientUrl("~/masterpages/js/unitpngfix.js") %>" type="text/javascript"></script>

A) you can declare both the src attribute for a Javascript resource and information within the block. You'd need to do declare the clear in it's own block prior to the src block

B) The way I've accomplish passing code-generated URLs to Javascript is in my view/masterpage I have a script block that declares a url array attached to the Window so that way there isn't odd conflicts down the road with other scripts:

<script type="text/javascript">
   Window.url = {
       clearImage: '<%= ResolveClientUrl("~/masterpages/img/clear.gif") %>',
       otherUrl: '<%=ResolveClientUrl("~/other/file/...")%>'
   };
</script>

then in your actual script files you can get it via

var img = window.url.clearImage;

It does bind the script to that specific view, but I don't see that as a horrible thing.

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