How do I load a selectable javascript in html header

2.4k views Asked by At

I'm looking for a way to select and load a javascript from the html file arguments. The html file is called as follows:

OSM_Map.html?year=2017 or OSM_Map.html?year=2018

In the OSM_Map.html file there is the following code in the header:

<head>
.....
<script language="JavaScript" type="text/javascript" src="LatLonDB_2017.js"></script>
<script language="JavaScript" type="text/javascript" src="LatLonDB_2018.js"></script>
....
</head>

There is no problem to get the year argument from the argument list, but how can I load depending on the year argument just one of these .js files?

2

There are 2 answers

0
Alex Angelico On

As somebody said, "yes, you can":

<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/loadjs/3.5.5/loadjs.min.js"></script>
   <script>
      var myparameter = new URL(location.href).searchParams.get("year");
      loadjs( "LatLonDB_" + myparameter +".js" );
    </script>

</head>
<body>
    <h1>Titulo</h1>
</body>
</html>

Been the URL something like: http://test.html?year=2018

BUT! not sure if this will work in every browser.... the "searchParams" is not universally compatible.

Thanks to @spencer.sm in this question How to get the value from the GET parameters?

and of course, loadJS function.

0
Rob Udo On

The LatLonDB_xxxx.js script still doesn't load. I'm not sure why not. Cannot you load a .js file from another directory than where the .html file is? Otherwise the load may be too late. Scripts following the LatLonDB_xxxx.js script use this DB.

The original code is like this:

<html>
<head>
  ...
  <script language="JavaScript" type="text/javascript" src="../DataBases/LatLonDB_20xx.js"></script>
  <script language="JavaScript" type="text/javascript" src="../DataBases/LatLonDB_utils.js"></script>
  <script language="JavaScript" type="text/javascript" ...more scripts using the LatLonDB_20xx.js></script>
  ...
</head>
...
</html>

The intention is to replace the 20xx by the correct year: 2000, 2001, etc. There is no problem to get the correct year from the query parameters.