简体   繁体   中英

dynamically add route to script src on an html page

i want to dynamically add route to script src on an html page. for example,

<script src="../../../library/vendor/jquery/jquery-3.1.1.min.js"></script>

when i use web server and load this code, not working. maybe it should put web server url prefix. so i want to change below.

<script src="mySite/../../../library/vendor/jquery/jquery-3.1.1.min.js"></script>

or, other things that root-relative path set?

This cannot be achieved by html or javascript only. You need at least a framework which is able to "render" your html before it is send to your browser and replace "mySite".

Example in JSF 2.x it would look like this:

<link href="#{request.contextPath}/css/style.css" rel="stylesheet" type="text/css"/>

Or Thymeleaf:

<a th:href="@{/order/list}">

If you want to develop for example a one page site, where the content is replaced dynamically by ajax, then you need at least one page which is dynamically created by one of this frameworks.

Use below JavaScript code:

    var scr = document.createElement('script');
    var myurl = 'http://example.com/myjavascript.js'
    scr.setAttribute('src',myurl);

    document.head.appendChild(scr);

or you can create a function like this:

function addMyScript(url) {
  var scr = document.createElement('script');
  scr.setAttribute('src', url);
  document.head.appendChild(src);
}

you can dynamically decide your url and call the function by passing it as a parameter:

addMyScript('http://example.com/myjavascript.js');

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