Skip to content Skip to sidebar Skip to footer

Best Way To Access External JavaScript File And Place Contents In Div?

So, lets say you have a page that wants to load from a javascript file and it includes temp.html file

Solution 1:

Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).

You can try this approach:

<script src="example.js" onload="getInfo();"></script>

In your example.js, change getInfo() to something like this:

function getInfo() {
  $(document).ready(function() {
      var place = "foo"
      $(".one").html(place);
  });
}

Solution 2:

Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.

A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.

    <div id="rdy">
    </div>
</body>

Then in your file:

   $('#rdy').ready(getInfo);

Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.


Solution 3:

If we assume you have a JavaScript file that contains this content:

function getInfo() {
    var place = "foo"
    $(".one").html(place);
}

then your markup will look something like this:

<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="example.js"></script>
        <script>
            $(function(){
                getInfo();
            });
        </script>
    </head>
    <body>
        <p class="one"></p>
    </body>
</html>

$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.


Post a Comment for "Best Way To Access External JavaScript File And Place Contents In Div?"