I want to...">

How to conditionally include an external javascript file?

I have this code:

<script src="http://external/js/file/url.js"> </script> 

I want to do something like this -

 <script> if(2>1){ //include http://external/js/file/url.js } </script> 

Any idea?

+5
source share
3 answers

This question was asked earlier in Include a Javascript file in another Javascript file . This piece of code may match what you were looking for

 function include(filename) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.src = filename; script.type = 'text/javascript'; head.appendChild(script) } 

if this script does not work, I suggest you view and read the message above: Include the Javascript file in another Javascript file .

I hope this helps, maybe this is not the answer you were looking for, but it might just help.

+11
source

You just load it asynchronously, like

 if(yourCondition==true){ var d = document, h = d.getElementsByTagName('head')[0], s = d.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'http://external/js/file/url.js'; h.appendChild(s); } 
+5
source

You can use something like:

 <script type="text/javascript"> if (condition == true) { document.getElementsByTagName("head")[0].innerHTML += ("<script src=\"http://external/js/file/url.js\" type=\"text/javascript\"></script>"); } </script> 
+3
source

Source: https://habr.com/ru/post/1207063/


All Articles