Evaldas
Evaldas

Reputation: 5

How to lazy-load an inline javascript?

I want to load a banner ad script only when specific div is reached. For example - banner div at the bottom of the page.

I can load external scripts by using jquery lazy script:

var options = {
    type: "visible",
    id:"mydiv", //div Id
    scripts: [
        "1.js",
        "2.js",
        "3.js"
            ],
    success: function () {

    }
};
$.lazyscript(options);

But how to load inline scripts?

Thanks.

Upvotes: 0

Views: 1497

Answers (2)

emn178
emn178

Reputation: 1492

You can try my project jquery-lazyload-any

Html

<div id="you-want-lazyload">
  <!--
    <script>doSomething();</script>
  -->
</div>

JavaScript:

$('#you-want-lazyload').lazyload(options);

or other one jquery-appear

Html

<div id="you-want-to-detect">
</div>

JavaScript

$('#you-want-to-detect').bind('appear', doSomething); // you have to unbind event if you want to trigger only once

Upvotes: 0

grossadamm
grossadamm

Reputation: 452

The entire html document is parsed top to bottom, script tags included. So in that sense, your inline javascript is "loaded." I may be misunderstanding your question.

If you didn't want your inline script to be executed as soon as it was parsed you would need to use some kind of event listener in the inline script.

For example, assuming your inline banner ad code is wrapped in a function

<script>
loadBannerScriptAd()
</script>

you would need to write something like

<script>
$(document).on("loadBannerScript", loadBannerScriptAd)
</script>

which you could trigger at any point by

$(document).trigger("loadBannerScript")

All of this is assuming you have jquery based on your code sample you gave above. Check out http://api.jquery.com/trigger/ for detailed information on how you could trigger custom events via jquery.

Upvotes: 1

Related Questions