How to lazy-load an inline javascript? - 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.

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.

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

Related

Alternative to hide/show content with JS?

is there a better way to replace this kind of js function by simply collapse/toggle a div and show/hide its content?
$(function() {
$('#destselect').change(function(){
$('.dest').hide();
$('#' + $(this).val()).show();
});
});
The reason this is happening is because your js file is called on the head of your page.
Because of this, when you document.getElementsByClassName('collapsible');, colls result in an empty array, as your elements in body are not yet created.
You could either create a separate js file and add it at the end of your body (in that way you make sure your colls are created when your javascript is executed), or just wrap your code on a DOMContentLoaded event listener that will trigger your code once the document has completely loaded.
My guess would be that you are loading your script before browser finishes loading dom conetent and so when it runs the elements it is trying to add event listeners to, don't yet exist.
Try wrapping all you javascript in that file in this:
document.addEventListener("DOMContentLoaded", function(event) {
// all your code goes here
});
The above makes sure that your script is run after loading all elements on the page.
You could add a script tag to the header of your HTML file, this will import the JS file into your current page as follows
<script src="File1.js" type="text/javascript"></script>
Then call the function either in onclick in a button or in another script (usually at the bottom) of your page. Something like this:
<body>
...
<script type="text/javascript">
functionFromFile1()
</script>
</body>
Seems like your script is not executing properly due to a missing variable.
In this script https://www.argentina-fly.com/js/scripts.js
Naves variable in function UpdateDetailsDestination() is not defined.
I think you should resolve this first and then check your further code is working on not.
Please take a look into Console when running page. You'll see all JavaScript related errors there.

Rerun inline scripts at end of external script function

I built a site for a client where I have a script which moves a sidebar div below the main content when in mobile view. This script is loaded in the footer:
// Move Global nav to top for mobile
$(window).on("resize", function() {
var windowSize = $(window).innerWidth();
if(windowSize > 767){
$(".utility-nav").insertBefore($(".global-nav"));
$(".sidebar-secondary").insertAfter($(".subnav"));
} else {
$(".global-nav").insertBefore($(".utility-nav"));
$(".sidebar-secondary").insertAfter($(".content-main"));
}
}).resize();
They are adding a third party calendar which requires them to insert code snippets that include inline scripts. When these are placed in the .sidebar-secondary div, which is moved for mobile, the content disappears. I assume that, since my script is running after these have initiated, they are being canceled out.
Is there a way to just have my script rerun any inline scripts within that div?
Here is the page they are testing:
http://www.umary.edu/sandbox-training/index.php
The scripts in the left sidebar are the ones that are malfunctioning.
Thank you!
You can retrieve all the script tags within your div and eval the text inside them
$('#run').click(function(){
$('#someSideBar').find('script').each(function(){
eval( $(this).text() );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someSideBar">
<script type="text/javascript">
alert('hello');
</script>
<script type="text/javascript">
alert('there');
</script>
</div>
<input type="button" id="run" value="Run">
** You should research the security implications of this before proceeding.
The reason your content disappears is because the <iframe>s that hold your content are unloaded when they are detached from the DOM, and loaded upon attaching them to the DOM again. Since the <iframe>s in question seem to be generated by a script, the second load yields an empty document. See this simple DOM test-case for seeing that load/unload bevhavior. As far as I can tell there is no way to move an iframe in the DOM in such a way that this behavior is prohibited.
You explicitly ask for this, but simply rerunning the inline <script>s may not yield the results you hope for, unless these scripts are (accidentally or purposefully) written in such a way that allows this. Be very careful with this sort of stuff. If there is a single document.write() your entire document would be overwritten. This is usually not the kind of destructive power you'd want to hand to a third party script.
You could try rearranging your content using Flexbox and the order property, so content is moved in CSS and not the DOM.
You could try rearranging the other content in such a way that you don't need to move .sidebar-secondary in the DOM. You may need to split the secondary content block into a separate <div role="complimentary"> (btw. that's what <nav> is for). Once that is done, you can move #content-start before the container of .sidebar-secondary.

jQueryTOOLS Overlay lightbox not functioning when HTML/LINK is loaded via ajax

Before starting, I have researched and found this similar, previous question: Reinitialize jQuerytools Overlay on ajax loaded element
However, the "answer" to that question suggests using .live(). I attempted to us jQuery 1.9 .live() is not a function to update using .on().
$(".overlay_load[rel]").on('click', 'a', function () {
$(this).overlay().load();
$(this).overlay().load();
return false;
});
I will admit I don't 100% understand exactly what that is doing other than perhaps re-initializing the newly loaded HTML so that jQueryTOOLS Overlay has 'access' to the newly loaded HTML.
I have a page loading sections of HTML content via AJAX. Here is an example of one DIV that is loaded.
<div class="ajax-returned mytop">
<span class="username"> drkwong </span> <br>
<span class="full-name">Andrew Kwong</span><br>
<span class="action-status">
<span class="mt-icon ut3"></span>
<span class="autoship active">A</span>
<span class="view_profile">
<a href="/member/downline_tree_view/?view=tree_profile&program=1&view_userid=13" rel="#overlay">
<img src="/inc/downline_tree/images/more_info.png" rel="#13">
</a>
</span>
</span>
</div>
<!-- overlayed element -->
<div class="apple_overlay" id="overlay">
<!-- the external content is loaded inside this tag -->
<div class="contentWrap"></div>
</div>
This has a link that should engage a jQuery and then load a jQueryTOOLS Overlay lightbox:
<script>
$(function() {
// if the function argument is given to overlay,
// it is assumed to be the onBeforeLoad event listener
$("a[rel]").overlay({
mask: 'grey',
effect: 'apple',
onBeforeLoad: function() {
// grab wrapper element inside content
var wrap = this.getOverlay().find(".contentWrap");
// load the page specified in the trigger
wrap.load(this.getTrigger().attr("href"));
}
});
});
</script>
This is the jQuery I am using to load an external page into a Light Box: http://jquerytools.github.io/demos/overlay/external.html
It simply feels like it's not triggering the jQuery.
Here's what's in the header:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="/templates/public/2/downline/js/jquery.browser.min.js"></script>
<script type="text/javascript" src="/templates/public/2/downline/js/jquery.tools.min.js"></script>
The jquery.browser.min.js is required by jQueryTOOLS Overlay to access browsers. https://github.com/gabceb/jquery-browser-plugin
EDIT:
AJAX
var ids=new Array()
var node
var param={"action":"NodeDetailAll","admin":"1"}
var users=new Array()
function get_ids(){
for(var i=0;i<nodes.length;i++){
users.push("child_"+$(nodes[i]).attr("class"))
ids.push($(nodes[i]).attr("class"))
}
}
function get_nodes(){
nodes = $("#chart [myattr*='descendent']")
nodes= jQuery.makeArray(nodes);
$.when(get_ids()).then(function(){
$.each(ids,function(key,value){
param[users[key]]=value
})
})
}
function write_html(response){
$.each(response,function(key,value){
$("."+key).html(value)
})
}
jQuery(document).ready(function() {
$(".spinner-loader").fadeIn(200)
$.when(get_nodes()).then(function(){
$.post("~ajax_url~",param,function(response) {
response=jQuery.parseJSON(response)
$.when(write_html(response)).done(function() {
$(".spinner-loader").fadeOut(600)
$("#chart").css("opacity","1")
// is this where I would add the on()? //
// I tried that, without success. //
// perhaps I need to modify the on() function? //
})
})
})
})
You could call the overlay binding on the callback of your ajax function. The other thing would be is to check your jQuery selectors to make sure you have them configured appropriately and that they are selecting the appropriate element to bind your event to.
As per the jQuery documentation: "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
so it does seem to me that calling the binding functionality in the callback of your AJAX request would be the way to go! Perhaps if you could provide a simplified version of your code, ajax request included then I could try and take another look :)
Use a different solution. jQueryTOOLS Overlay is no longer active and uses deprecated and even eliminated jQuery functions. Trying to solve all those issues has proven both inefficient and so far as AJAX is related, impossible with the latest versions of jQuery.
As suggested by #sparky FancyBox 2 provided the needed solution. It was simple and intuitive to implement.

How to bind a future event when using jQuery Mobile external page linking?

In jQuery Mobile, the external page is linked via Ajax (i.e. the content of the external page is loaded into current page via Ajax).
The problem is: How to bind a event on the future (i.e. to be loaded) content?
Let say the content to be loaded has the following HTML input
<input type='text' id='foo' name='foo'>
How to bind a input event on it?
With just static HTML, the following code would work
$('#foo').on('input', function () {
...
Now it didn't work now since the DOM is loaded dynamically, I tried to use delegation but also not work
$(document).on('#foo', 'input', function () {
...
Any idea?
You can include the script in the external page as long as the script tag is within the data-role="page" div (Only the content of the first found data-role="page" element is loaded into the current page.
$(document).on("pagecreate", "#extpagedivid", function(){
$(document).on("input", "#foo", function(){...});
});
You can also include this code in the pagecreate handler of the main page as long as you are using event delegation. Make sure the ID of the input is unique across all pages that will be loaded into the main page.
How about using var
var myFunc = function() { ... }
$(document).ready(function() {
$('#foo').on('input', myFunc );
});

HTML & JS Markup - better way possible?

I'm loading my html files into a #content div in order to avoid the complete page to reload when clicking on a link. I'm doing this by calling the following in my index.html:
[...]
<div id="content">
<script type="text/javascript">$("#content").load("home.html");</script>
</div>
The problem is that no javascript in my global.js will be executed if it's related to one of the html files that will be loaded into my #content div.
In order to handle that fact I simply put the js of the related html file right into that specific one by posting it with the <script> command, e.g. like this:
<script type="text/javascript">
$(document).ready(function () {
$(".faq").click(function () {
$(this).find(".faq_answer").toggle();
});
});
</script>
I'm totally unhappy with it and so my question is: is there a way I could put my js back in my global.js file?
If I understand correclty your question, you need to use even delegation to assign event handlers to elements that doesn't exist yet
$(document).on("click",".faq", function (){ ... })
Where document can be replaced by any container of .faq that exists at bind time.
For more details check "Direct and delegated" section here
Try to load the page through your global.js inside of keeping it in your html page.
Keep the script that will load the content first.
This should work

Categories

Resources