Use JS variable to set the src attribute for [removed] tag

前端 未结 5 597
后悔当初
后悔当初 2020-12-10 10:11

I want to use a javascript variable as a \'src\' attribute for another tag on the same jsp.



        
相关标签:
5条回答
  • 2020-12-10 10:46
    <xsl:variable name="Path" select="/root/folder/"></xsl:variable> <!-- Global path variable. -->
    <xsl:variable name="myScriptPath" select="concat($Path, 'myScript.js')"></xsl:variable> <!-- Relative script path variable. -->
    <script src="{$myScriptPath}"/> <!-- Attach script. -->
    
    0 讨论(0)
  • 2020-12-10 10:50

    I use something similar to choice two. There is a slight mistake in your code because "google.com" needs to be surrounded by quotes.

    To improve compatibility, you might want to write it as:

    document.write("<script type='text/javascript' src='"+ x + "'><\/scr" + "ipt>");
    

    In this situation, x would be the file to be included. You can define it as:

    var x = "http://google.com/script.js";
    

    OR

    var x = "path/to/script.js";
    
    0 讨论(0)
  • 2020-12-10 10:57

    Though CDATA works fine, using document.createElement is also a great choice.. Especially if you intend to append some value to a URL, say for cache busting..

    <script type="text/javascript"> 
        var JSLink = "/Folder/sub_folder/version.js?version=" + Math.random();
        var JSElement = document.createElement('script');
        JSElement.src = JSLink;
        JSElement.onload = OnceLoaded;
        document.getElementsByTagName('head')[0].appendChild(JSElement);
    
        function OnceLoaded() {
            // Once loaded.. load other JS or CSS or call objects of version.js
        }
    </script>
    

    Code well.. :)

    0 讨论(0)
  • 2020-12-10 11:01

    Try:

    (function(d){
         var file = 'yourJS.js';
         var ref = d.getElementsByTagName('script')[0];
         var js = d.createElement('script');
         js.src = file;
         ref.parentNode.insertBefore(js, ref);
    }(document));
    

    What this does:

    1. Find the first script element on your page
    2. Creates a new script element with your supplied source.
    3. Then inserts that new element before the first existing script element.
    0 讨论(0)
  • 2020-12-10 11:05

    Are you able to use jQuery? If so you could use getScript():

    http://api.jquery.com/jQuery.getScript/

    $.getScript(mylink, function() {
       // do something using the JS that was loaded.
    });
    
    0 讨论(0)
提交回复
热议问题