Andy T
Andy T

Reputation: 9881

Convert embedded JavaScript into ajax call

I am currently embedding a third-party javascript file directly on my page.

However, the website I'm embedding it from takes a while to respond so it stops the rendering of my site for several seconds.

I'm currently embedding it on my page on the spot where it will write some values:

<script language="javascript" type="text/javascript" src="[third-party site/file.js]"></script>

The response from the embedded script is just some JavaScript:

document.write('<div class="value">Value 1</div><div class="value">Value 2</div>');

I was thinking that after the page loads use jQuery to make an AJAX request and somehow parsing the response so I can get the values I need.

Is there be a better approach?

Upvotes: 0

Views: 646

Answers (3)

cssyphus
cssyphus

Reputation: 40038

Perhaps this could be part of your solution. Here is a stand-alone jQuery example where a button is used to trigger a change event on a DIV. This example just shows you how to access the html content of the div and to see how to manipulate/change it. This is not a solution for you but parts of it might be useful when combined with rcdmk's and James' ideas.

<html>
    <head>
        <!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>-->
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                $('#button_test').click(function() {
                    $('.value').html('New stuff').change();
                });
                $('.value').change(function(){
                    $('div').each(function() {
                        alert($(this).html());
                    });
                });
            });
        </script>
    </head>
<body>


<div class="value">Value 1</div>
<div class="value">Value 2</div>
<button id="button_test">Click me</button>

Upvotes: 0

Ricardo Souza
Ricardo Souza

Reputation: 16446

You can place this script inside a hidden element on the end of the body (just before </body>) and, after the page has loaded, move it to the desired location with jQuery.

    <div id="hiddenElement">
        <script type="text/javascript" src="[third-party site/file.js]"></script>
    </div>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#hiddenElement").appendTo("#someOtherElement");
        });
    </script>
</body>

Another solution would be to use jQuery .getScript() to load the script in the desired location as you said and @James McDonnell said.

Upvotes: 1

James McDonnell
James McDonnell

Reputation: 3710

$(document).read(function()
{
  $.getScript(/* src */)
});

This will run after the page has loaded.

$.getScript()

Upvotes: 0

Related Questions