I currently have a site I am working on where there is a script that only needs to be loaded and shown when a certain element is clicked. The script we are loading is external and very slow to load and blocks the dom from loading as fast as it should. I am looking to append this script or load its contents into a certain element on click. I have looked high and low and have tried many different methods to do this with no success. I know this is possible and have done this before but cannot remember how.
Note that I have tried loading the contents of the url into an iframe then cloning and adding to the element.
The code below illustrates what I am looking to do
$("#button").click(function(e){
e.preventDefault();
var $slowLoadingScript = $('<script src="http://external-slow-script.com/script.js"></script>');
$slowLoadingScript.load(function(){
$("#Element").append(slowLoadingScript);
});
});
Note the contents of the script look like this:
document.write("a long list of html and js");
$('#button').click(function(e){
e.preventDefault();
$.getScript('http://external-slow-script.com/script.js');
});
Explanation for jQuery's $.getScript() at http://api.jquery.com/jQuery.getScript/.
Related
I've searched other articles and jQuery documentation, but have not quite found (or understood) the solution I need.
I'm including Sharing buttons on our site using another online service. The procedure is to add a snippet of HTML (a closed with a specific class name) and include a call to their Javascript file.
<div class="specific_class_name"></div>
<script type="text/javascript" src="path to script.js#pubid=my-account-id" async="async"></script>
This works well on pages for which I have access to edit HTML and include scripts.
My challenge is how to include the Share buttons on pages for which I only have access to run Javascript and not to include specific HTML. I can add the closed element using jQuery .append and include the Javascript call, but this does not work as needed. If I inspect the page after it is fully loaded, I see that the dynamic element has been added correctly and the script has been called. Viewing the Page Source, the is not present.
Of course, I have no means of editing this service's script. I need the called script to find the dynamic element either during or following page load, not following any user / mouse action.
Thanks for any feedback.
Create the div and then use the getScript command to include it like:
$(window).on('load', function(){
$('<div class="class_name"></div>').appendTo("someIDyouhave");
$.getScript('path to script.js#pubid=my-account-id');
});
http://api.jquery.com/jquery.getscript/
Have you tried something like this? Append the element and then add a click event?
$(function() {
var appendedElement = $('<div id="myID"></div>')
$('.specific_class_name').append(appendedElement).on('click', '#myID', function(){
whatever();
});
});
This should work.
I'm having a jQuery mobile page with JavaScript inside. The problem is the JavaScript doesn't work unless the page is refreshed. Here is my code:
jQuery(function($) {
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
To understand this problem you need to understand how jQuery Mobile works.
Your first problem is point where you are trying to initialize JavaScript. From your previous answers I can see you are using several HTML/ASP pages and all of your javascript is initialized form the page <head>. This is the main problem. Only the first HTML file should have JavaScript placed into the <head> content. When jQuery Mobile loads other pages into the DOM it loads only the <div> with a data-role="page" attribute. Everything else, including <head>, will be discarded.
This is because currently loaded page has a <head> already. No point in loading another pages <head> content. This goes even further. If you have several pages in a second HTML file, only the first one is going to be loaded.
I will not try to invent warm water here so here are links to my other 2 answers discussing this problem. Several solutions can be found there:
Why I have to put all the script to index.html in jquery mobile (or in this blog article)
Link fails to work unless refreshing
There's more then enough information there to give you an idea what to do.
The basic solutions to this problem are:
Put all of your JavaScript into a first HTML/ASP file
Move your JavaScript into <body>; to be more precise, move it into a <div> with data-role="page". As I already pointed out, this is the only part of a page that is going to be loaded.
Use rel="external" when switching between pages because it will trigger a full page refresh. Basically, you jQuery mobile that the page will act as a normal web application.
As Archer pointed out, you should use page events to initialize your code. But let me tell you more about this problem. Unlike classic normal web pages, when working with jQuery Mobile, document ready will usually trigger before page is fully loaded/enhanced inside the DOM.
That is why page events were created. There are several of them, but if you want your code to execute only once (like in case of document ready) you should use the pageinit event. In any other case use pagebeforeshow or pageshow.
If you want to find out more about page events and why they should be used instead of document ready take a look at this article on my personal blog. Or find it here.
Your question isn't exactly overflowing with pointers and tips, so I'm going with the thing that immediately sprung to mind when I saw it.
Document ready does not fire on page change with jQuery Mobile, due to "hijax", their method of "ajaxifying" all the links. Try this instead...
$(document).on("pageshow", function() {
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
Try pageinit like this
$(document).delegate("body", "pageinit", function() { // Use body or page wrapper id / class
var url = window.location.search.substring(1);
$('#mydiv').load('real_news.asp?' + url);
});
seems like nothing ever worked for me. Tried many different fixes, but i made the site too messy, that even position of certain javascript files wouldn't make the site work. Enough talk, here is what i came up with.
// write it in head at top of all javascripts
<script type="text/javascript">
$(document).ready(function() {
// stops ajax load thereby refreshing page
$("a,button,form").attr('data-ajax', 'false');
// encourages ajax load, hinders refresh page (in case if you want popup or dialogs to work.)
$("a[data-rel],a[data-dialog],a[data-transition]").attr('data-ajax', 'true');
});
</script>
jquery recommended way to do ajax navigation
I just tried out this simple jquery ajax code to load all the links in a page in an ajax manner.
$('a').click(function(e){
e.preventDefault();
url = $(this).attr('href');
$('body').fadeTo('slow', 0.2);
$('body').load(url, function(data){
$(this).fadeTo('slow', 1, function(){
$(this).html(data);
scroll(0,0);
});
});
});
[The links in the page stick to the current domain and no external links are present]
The page load works as expected but the scripts for Facebook, LinkedIn, pinterest buttons fail to load.
I think this is not the safest way to do a ajax navigation and I am sure other JS files, inline JavaScripts will cause error.
http://davidwalsh.name has some good ajax navigation work with mootools. I am trying to achieve the same using jquery.
The website loads and executes every script successfully and it is seen that the ajax work is not done to load specific scripts.
Is there any safe way to achieve this, making sure that the ajax loaded page works as normal as it should ??
You should call the function that attaches the script inside the load handler, so it re-attaches all DOM scripts on each load.
F.ex, if you have this code:
$(document).ready(function() {
$('#facebook').doFacebook();
$('#twitter').doTwitter();
});
Change it to:
var onload = function() {
$('#facebook').doFacebook();
$('#twitter').doTwitter();
};
$(document).ready(onload);
Then just call onload whenever the body gets new content.
Inline scripts should execute according to the docs.
You might also want to read up on how to manipulate browser history and URL using .pushState:
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries
There are decent jQuery plugins that adds this functionality in a cross-browser manner if you google around a bit.
Twitter generates me box code to insert on page: http://pastebin.com/5TgkL5vP but on slow connection it prevent page from loading. Is there any way to add "Loading..." and make it async? (I know about iframe but its awful way)
There is a solution in here;
http://od-eon.com/blogs/stefan/asynchronous-loading-twitter-widgets/
$(window).load(function(){
$.getScript('http://widgets.twimg.com/j/2/widget.js', function(){
$.getScript('/media/js/twitter.js', function(){
$('#twtr-widget-1').appendTo('#twitter_p')
})
})
})
To delay the loading of the twitter widget you could load it after your whole page is loaded. You could use the window's onload event handler to start loading the twitter widget once your page has been downloaded.
Or you could use a javascript library (like jquery) to run that code once you HTML is loaded but images and CSS and other assets are still loading: jquery's .ready() method does just that.
In case you don't want to use bare javascript (although recommended for learning) jquery (like others) does provide a .load() event that behaves just like the onload example on W3c.
In any case, with any of those two methods you could place a "loading..." text in a placeholder and then replace it with the widget once it's loaded.
You should try experimenting with both and see which one produces the best perceived results. Sometimes you want the page's content to load blazingly fast, in that case you should hold all external content from being loaded until the content is loaded (using onload or .load()), while sometimes you want everything to be loaded more or less at the same time (using .ready()).
I hope it didn't come out backwards :D.
The solution explain by od-eon.com is OK but for IE the CSS is not correctly added because it tries to add CSS in a window onload event. This event is fired asynchronously so no CSS is added.
The line $('#twtr-widget-1').appendTo('#twitter_p') is not useful.
You must not add a CSS position attribute to the div which will contain the box because nothing is displayed in this case. If you want to add this box in an absolute div you must add an empty div in it and pass the div's id in parameter.
I would like to set up a lean and mean image gallery, with thumbnails displayed inline. I'd like them not to windowshade in while loading, I'd like them to simply pop up or, if there's a way to detect their completion, use a jQuery effect like a quick fadeIn().
I imagine a line of code like:
$(".thumb-image").whenLoaded(fadeIn(500));
But is there such an event? What's it called?
Use the load event:
jQuery:
$(window).load(function(){
// your code for images....
});
Or Vanilla JavaScript:
window.onload = function(){
// your code for images....
};
The load event fires after all images, DOM, external resources, frames, etc have loaded.