Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to load an API and a JS file dynamically

I am trying to load Skyscanner API dynamically but it doesn't seem to work. I tried every possible way I could think of and all it happens the content disappears.

I tried console.log which gives no results; I tried elements from chrome's developers tools and while all the content's css remains the same, still the content disappears (I thought it could be adding display:none on the html/body sort of). I tried all Google's asynch tricks, yet again blank page. I tried all js plugins for async loading with still the same results.

Skyscanner's API documentation is poor and while they offer a callback it doesn't work the way google's API's callback do.

Example: http://jsfiddle.net/7TWYC/

Example with loading API in head section: http://jsfiddle.net/s2HkR/

So how can I load the api on button click or async? Without the file being in the HEAD section. If there is a way to prevent the document.write to make the page blank or any other way. I wouldn't mind using plain js, jQuery or PHP.

EDIT:

I've set a bounty to 250 ontop of the 50 I had previously.

Orlando Leite answered a really close idea on how to make this asynch api load although some features doesn't work such as selecting dates and I am not able to set styling.

I am looking for an answer of which I will be able to use all the features so that it works as it would work if it was loading on load.

Here is the updated fiddle by Orlando: http://jsfiddle.net/cxysA/12/

-

EDIT 2 ON Gijs ANSWER:

Gijs mentioned two links onto overwriting document.write. That sounds an awesome idea but I think it is not possible to accomplish what I am trying.

I used John's Resig way to prevent document.write of which can be found here: http://ejohn.org/blog/xhtml-documentwrite-and-adsense/

When I used this method, I load the API successfuly but the snippets.js file is not loading at all.

Fiddle: http://jsfiddle.net/9HX7N/

like image 860
jQuerybeast Avatar asked Nov 20 '11 03:11

jQuerybeast


People also ask

Is it possible to dynamically load external JavaScript files in JavaScript?

Dynamic loadingThose files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.

How do I load a JavaScript file asynchronously?

A very common solution to this issue is to put the script tag at the bottom of the page, just before the closing </body> tag. In doing so, the script is loaded and executed after all the page is already parsed and loaded, which is a huge improvement over the head alternative.

How do I load a JavaScript script?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.

How do you load third party scripts dynamically in react?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.


2 Answers

I belive what you want is it:

function loadSkyscanner()
{
    function loaded()
    {
        t.skyscanner.load('snippets', '1', {'nocss' : true});

        var snippet = new t.skyscanner.snippets.SearchPanelControl();
        snippet.setCurrency('GBP');
        snippet.setDeparture('uk');
        snippet.draw(document.getElementById('snippet_searchpanel'));
    }

    var t = document.getElementById('sky_loader').contentWindow;
    var head = t.document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.onreadystatechange= function() {
        if(this.readyState == 'complete') loaded();
    }
    script.onload= loaded;
    script.src= 'http://api.skyscanner.net/api.ashx?key=PUT_HERE_YOUR_SKYSCANNER_API_KEY';
    head.appendChild(script);
}

$("button").click(function(e)
{
    loadSkyscanner();
});

It's load skyscanner in iframe#sky_loader, after call loaded function to create the SearchPanelControl. But in the end, snippet draws in the main document. It's really a bizarre workaround, but it works.

The only restriction is, you need a iframe. But you can hide it using display:none.

A working example

EDIT

Sorry guy, I didn't see it. Now we can see how awful is skyscanner API. It puts two divs to make the autocomplete, but not relative to the element you call to draw, but the document. When a script is loaded in a iframe, document is the iframe document.

There is a solution, but I don't recommend, is really a workaround:

    function loadSkyscanner()
{
    var t;
    this.skyscanner;
    var iframe = $("<iframe id=\"sky_loader\" src=\"http://fiddle.jshell.net/orlleite/2TqDu/6/show/\"></iframe>");

    function realWorkaround()
    {
        var tbody = t.document.getElementsByTagName("body")[0];
        var body = document.getElementsByTagName("body")[0];

        while( tbody.children.length != 0 )
        {
            var temp = tbody.children[0];
            tbody.removeChild( temp );
            body.appendChild( temp );
        }
    }

    function snippetLoaded()
    {
        skyscanner = t.skyscanner;

        var snippet = new skyscanner.snippets.SearchPanelControl();
        snippet.setCurrency('GBP');
        snippet.setDeparture('uk');
        snippet.draw(document.getElementById('snippet_searchpanel'));

        setTimeout( realWorkaround, 2000 );
    }

    var loaded = function()
    {
        console.log( "loaded" );
        t = document.getElementById('sky_loader').contentWindow;

        t.onLoadSnippets( snippetLoaded );
    }

    $("body").append(iframe);
    iframe.load(loaded);
}

$("button").click(function(e)
{
    loadSkyscanner();
});

Load a iframe with another html who loads and callback when the snippet is loaded. After loaded create the snippet where you want and after set a timeout because we can't know when the SearchPanelControl is loaded. This realWorkaround move the autocomplete divs to the main document.

You can see a work example here

The iframe loaded is this

EDIT

Fixed the bug you found and updated the link.

the for loop has gone and added a while, works better now.

    while( tbody.children.length != 0 )
    {
        var temp = tbody.children[0];
        tbody.removeChild( temp );
        body.appendChild( temp );
    }
like image 137
Ratata Tata Avatar answered Oct 01 '22 08:10

Ratata Tata


For problematic cases like this, you can just overwrite document.write. Hacky as hell, but it works and you get to decide where all the content goes. See eg. this blogpost by John Resig. This ignores IE, but with a bit of work the trick works in IE as well, see eg. this blogpost.

So, I'd suggest overwriting document.write with your own function, batch up the output where necessary, and put it where you like (eg. in a div at the bottom of your <body>'). That should prevent the script from nuking your page's content.

Edit: OK, so I had/took some time to look into this script. For future reference, use something like http://jsbeautifier.org/ to investigate third-party scripts. Much easier to read that way. Fortunately, there is barely any obfuscation/minification at all, and so you have a supplement for their API documentation (which I was unable to find, by the way -- I only found 'code wizards', which I had no interest in).

Here's an almost-working example: http://jsfiddle.net/a8q2s/1/

Here's the steps I took:

  1. override document.write. This needs to happen before you load the initial script. Your replacement function should append their string of code into the DOM. Don't call the old document.write, that'll just get you errors and won't do what you want anyway. In this case you're lucky because all the content is in a single document.write call (check the source of the initial script). If this weren't the case, you'd have to batch everything up until the HTML they'd given you was valid and/or you were sure there was nothing else coming.
  2. load the initial script on the button click with jQuery's $.getScript or equivalent. Pass a callback function (I used a named function reference for clarity, but you can inline it if you prefer).
  3. Tell Skyscanner to load the module.

Edit #2: Hah, they have an API (skyscanner.loadAndWait) for getting a callback once their script has loaded. Using that works:

http://jsfiddle.net/a8q2s/3/

(note: this still seems to use a timeout loop internally)

like image 21
Gijs Avatar answered Oct 01 '22 09:10

Gijs