Adding Javascript Dynamically With DOM Scripting

The Document Object Model, or DOM, is a representation of a website stored in the memory of a computer. JavaScript is used to add, alter and delete elements from the DOM such as links, images or text. One type of element that can be added to the DOM via JavaScript is a script element which can insert additional JavaScript code into the page even after the page has already loaded.

Instructions

    • 1

      Copy and paste the following code into the head of your HTML document:
      <script type="text/javascript">
      function dynamic_load(script_url)
      {
      var dynamic_script = document.createElement('script');
      dynamic_script.setAttribute("type","text/javascript");
      dynamic_script.setAttribute("crc",script_url);
      document.getElementsByTagName("head")[0].appendChild(dynamic_script);
      }
      </script>

    • 2

      Copy and paste the following code into the body of your HTML document:
      <a href="#" onclick="dynamic_load("MyScript.js")">Load MyScript.js</a>

    • 3

      Open your HTML document in a browser and click the link from Step 2. The contents of MyScript.js will load as soon as you do.

Tips & Warnings

  • If you just want to test whether the dynamic load works, place the following line at the top of MyScript.js:

  • alert("The load worked!");

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured