-1

How would one go about conditionally loading html/javascript in the body based on a variable using javascript.

something like:

<html>
<body>
<script type="text/javascript">
if (typeof variable1 === 'undefined') {
html elements and javascript functions/code here
}
variable1 = true;
</script>

one possible use is to avoid loading content more than once.

Ray S.
  • 1,122
  • 3
  • 12
  • 26

3 Answers3

1

You can do this but you need a small piece of server-side work. You see in your example...

<html>
<body>
<script type="text/javascript">
if (typeof variable1 === 'undefined') {
html elements and javascript functions/code here
}
variable1 = true;
</script>

variable1 is always undefined. So everything you want to hide by using that if statement will show/load. What you can do just before that is something like this...

<html>
<body>
<script type="text/javascript">
// try using localstorage
if (!localStorage.getItem("variable1")) {
html elements and javascript functions/code here
localStorage.setItem("variable1","loaded");
}
// later on you may have a function that removes the html and javascript that was added.
function foo() {
// function stuff
localStorage.removeItem("variable1"); // remove this so content may be able to load when needed.
}
</script>
  • if you please remove the down-vote since i am editing my answer @RayS. –  May 24 '16 at 21:01
  • Was my down vote... I removed it when you introduced local storage. – Louys Patrice Bessette May 24 '16 at 21:04
  • ok sorry @RayS. i thought it was you, logically down-votes go with comments . –  May 24 '16 at 21:05
  • localstorage does not clear unless you clear it by using `.removeItem()` or force clear by your browser's settings panel. @RayS. If you want to use it to store data and retrieve at any time then it will suit you in this. –  May 24 '16 at 21:09
  • how about document.write would that work? – Ray S. May 25 '16 at 05:11
-1

There's nothing that is parsed so in JavaScript. You can index write from document and call it, like this:

document.write("html elements and javascript functions/code here")

, though.

Klaider
  • 3,140
  • 3
  • 20
  • 49
-1

If I understood the question correctly, You need to change the DOM based on a variable. One way to do this is to create an object and add a listener function that will detect changes in the object. Here is one of many posts that has a solution.

Listening for variable changes in JavaScript or jQuery

I have a fiddle forked from the one in the answer above. I have changed the fiddle to reflect changes in html based on the value of an object.

https://jsfiddle.net/140Lm69f/

x.registerListener(function(val) {
    document.getElementById('eventBased').innerHTML = "Someone changed the value of x.a to " + val;
  Console.log("Someone changed the value of x.a to " + val);
});
Community
  • 1
  • 1
pparas
  • 530
  • 4
  • 13