Conditional branching by url content in html file

Asked 2 years ago, Updated 2 years ago, 74 views

Thank you very much for your help.I have the following html file, and I would like to conditionally branch the inclusion1.js or inclusion2.js above according to the contents of the p_id value obtained from url in the description below (e.g., 1 or 2). Could you tell me exactly what I should write?

<!doctype html>
<html>
<body>

<script type="text/javascript" src="include1.js"></script>

<script type="text/javascript" src="include2.js"></script>


<script type="text/javascript"> 
const url = new URL (location.href);
constp_id = url.searchParams.get("p_id");
</script>

<script type="text/javascript"> 
  document.addEventListener('DOMContentLoaded', function(){
  document.getElementById('p_id').value=p_id;   
});
</script>


</body>
</html>

*Statements tried by the professor

<!doctype html>
<html>
<body>

<script type="text/javascript"> 
const url = new URL (location.href);
constp_id = url.searchParams.get("p_id");

const script = document.createElement('script');
if(p_id==1){
  script.src = 'include1.js';
} else{
  script.src = 'include2.js';
}
document.body.appendChild(script);
</script>

<script type="text/javascript"> 
  document.addEventListener('DOMContentLoaded', function(){
  document.getElementById('p_id').value=p_id;   
});
</script>

</body>
</html>

javascript html

2022-09-30 21:43

1 Answers

Dynamic insertion of the script element is possible.

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript"> 
const url = new URL (location.href);
constp_id = url.searchParams.get("p_id");

const script = document.createElement('script');
if(conditions for p_id){
  script.src = 'include1.js';
} else{
  script.src = 'include2.js';
}
document.body.appendChild(script);
</script>

</body>
</html>

If the inserted script runs asynchronously, wait for the load event in the script element to take action.


2022-09-30 21:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.