changing script src onclick, will it execute once the page has loaded? - javascript

So lets say I have a script that loads immediately when you load a page.
But when you click on a button, the script src changes. Will that new src get executed?
HTML
<button>
click
</button>
<script class="tracking" src="www.gamespot.com"></script>
Javascript
$("button").on("click",function(){
$.ajax({
url: url,
dataType: "script",
success: console.log("success")
});
});
var url = "www.test.com";
I was actually thinking of appending the second script into the DOM when the button is clicked, but the results are funky on jsfiddle for some reason, so I'm not sure if that works..

Try to use RequireJS
Would be something like this:
var url = "www.test.com";
$("button").on("click",function(){
require(url, function() {
// callback that is executed after the script is loaded
});
});

Related

How to wait to finish loading page on button click using JavaScript/JQuery?

I am having an Anchor link, on click of Anchor link, I am registering new JavaScript file html page.
On registering the JavaScript file dynamically, document is reloaded partially (As I see reload icon in browser for some time).
I want to call my JavaScript function once the script got registered (Obviously when reload icon get stopped in the browser). But the function MyJavaScriptFunction got called while document is still reloading.
Using setTimeOut resolves the issue but I don't want to use it as page loading time is not fixed. Please help.
The code I am using is as follow:
function addScriptDynamically(src, callback) {
var s = document.createElement('script');
s.setAttribute('src', src);
s.onload = callback;
document.body.appendChild(s);
}
addScriptDynamically('URL Of JS File',function(){
MyJavaScriptFunction();
})
What I tried so far...
Option-1:
addScriptDynamically('URL Of JS File',function(){
$(document).ready(function(){
MyJavaScriptFunction();
});
})
Option-2:
addScriptDynamically('URL Of JS File',function(){
$(window).load(function(){
MyJavaScriptFunction();
});
})
jquery has a function for this purpose.
Using jquery
$(function () {
//write your function code here.
})
This function is called only when the content of the page are first loaded.
2)
Using Javascript
window.onload = function(){
//write your function code here.
}

How to show Page Loading html file until the page has finished loading?

I need a different page loader file (like: loader.html) in which i have only loader.gif image with some css styling not in the same index.html file. So now i want to load my index.html file before it loads i want to show my loader.html file and if my all content loaded hide the loader.html file and show index.html file content.
Hope you understand what i am saying please help :)
I tried this Code:
$(window).load(function(){
if($("body").load("loader.html").fadeOut(5000)){
$("loader.html").hide();
$("index.html").show();
}
});
.load( url [, data ] [, complete ] ) $.load
$(window).load(function(){
$("body").load("loader.html", function(){
/* place code need to executed after loader.html load */
});
});
You can do this:
On Page Load show your .gif or loader.html in some <div> as you required.
Make ajax call to load html.
After complete ajax call hide/remove .gif/loader.html and show your index.html.
This might solve your problem.
try this instead
On document.load function() show the loader .
On document.ready function() hide the loader`
jQuery
$(document).ready(function () {
//for demo, I used timer for 3 second
var timer = window.setTimeout(requestPage, 3000);
function requestPage(){
sendRequest("index.php", function(sResponse){
clearTimeout(timer);
//clear everything everything in body HTML
//change inner html with sResponse
$("body").children().fadeOut(300, function(){
$(this).remove();
$("body").html(sResponse)
});
});
}
function sendRequest(url, oncomplete){
$.ajax({
url: url,
type: 'POST',
dataType: 'html',
cache: false,
timeout: 60000,
complete: function(e, xhr, opt) {
if(typeof oncomplete === "function") oncomplete(e.responseText);
}
});
}
});
HTML
<div class="loader"><img src="loader.gif" /> <em>Loading page. Please wait...</em></div>
Hope you can help

Why is my div populated with my whole page?

I'm trying to load a div from another page using ajax but maintain the URL integrity using the History API. The ajax and history part is working (ie. the div is loading and the url is changing) but for some reason my div contains my entire page not just what is meant to be in the div!
This is the case for both the original page and the page div being loaded.
Stripped back HTML
<!DOCTYPE html>
<html>
<body>
<div id="slider">
... all the page content
<a rel='tab' href="p/password.jsf">Forgot password?</a>
</div>
</body>
</html>
JS
<script>
$(function(){
$("a[rel='tab']").click(function(e){
//get the link location that was clicked
pageurl = $(this).attr('href');
//to get the ajax content and display in div with id 'content'
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
//to change the browser URL to 'pageurl'
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
return false;
});
});
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
$('#slider').html(data);
}});
});
</script>
If you want to fetch an part of an page with ajax, then you can use the load method with the id of the element to fetch the content from.
$('#slider').load(pageurl + '?rel=tab #container_with_content_to_fetch', function() {
alert('callback after success.');
});
More info about load(): info
You may need to stop the default click action. It appears as though your link is acting as a... link.
$("a[rel='tab']").click(function(e){
e.preventDefault();
...
you if you want to select a specific part of the page that you recive with the ajax response
then do the following
/* the below code is to override back button to get the ajax content without reload*/
$(window).bind('popstate', function() {
$.ajax({
url:location.pathname+'?rel=tab',
success: function(data){
var mydiv = $('#my_div_id' , data ) // this will get the div with an id of #my_div_id
$('#slider').html(mydiv );
}});
});
$.ajax loads the whole page. You can use .load()
Instead of
$.ajax({
url:pageurl + '?rel=tab',
success: function(data){
$('#slider').html(data);
}});
you can use
$('#slider').load(pageurl + ' [rel=tab]');
The docs are here.

Hyperlink's click even not triggering in jQuery

Here is my full JS code:
var timeOutId;
function ft(){
$.get("progress.txt", null, function(data){
if(data.substr(0,10) == "MSG::MSG::"){
$("#box").html(data);
window.clearTimeout(timeOutId);
}else{
$("#box").html(data);
}
});
};
$(document).ready(function(){
$("#box").corner('20px');
$("#progress").hide();
});
$("#newm").click(function(){
$("#progress").show();
$("#list").html = $.ajax({
url: "action.php",
global: false,
type: "POST",
data: ({keyword : $("#keyword").value()},{format: $("#format").value()},{filename: $("#filename").value()},{list: $("#list").value()}),
dataType: "html"
});
timeOutId = window.setTimeout("ft()", 10000);
});
and there is a hyperlink with ID "newm" on page but clicking on the link doesnt trigger the ajax request. Can anyone tell me what is wrong?
Description
I have tryed your code and recognize that your binding to click is not working because the DOM element is not available at this time.
You should bind it under $(document).ready() to ensure the DOM is fully loaded before binding javascript / jquery to that.
This will enusre that your link will work, but its hard to help you without the html source.
If this will not help, please post the html.

How to update a value by jQuery AJAX

I load content of a page by jQuery AJAX as
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php?start="+$('#lastid').text(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
In the current document, I have <div id="lastid"></div> and in the external php file <div id="start"></div>
The value for id="start" is updated from database, and it will be transferred to id="lastid". However, this code only works for FIRST click. For default <div id="lastid">1</div>, when clicking the button (id="more") it will read load.php?start=1 and updates the current document to <div id="lastid">11</div> (it's visible). But the second click will not load load.php?start=11
It seems that $('lastid') well reads the default value of <div id="lastid"></div>, but NOT when it has been updated by $("#lastid").empty().load('html #start')
How can I modify this code to work for subsequent clicks?
Wow, what a mess! Let's clean up a bit :)
You need to get rid of the id, as an id has to be unique and if you load another div with id lastId into your site, jQuery will not know which id to get. If you have many divs, each containing the id, you can just read the last id by using ('div:last').text();
So your ajax would look like this:
$(document).ready(function(){
$('#next').click(function(event){
$.ajax({
url: "load.php",
data: "start="+$('div:last').text()
success: function(html){
$("#results").append(html);
}
});
});
});
I also don't know what you do with the last line in the success, as load should be used to load data from the server with ajax, what is what you do by using $.ajax(). Also load() takes at least an url as parameter, see here.
try .live() function instead of .click()
Mate,
What I see from you code is that you are attaching an event once the page is loaded. And this creates a static call with static values that don't get updated as you continue.
My suggestions is to use a function that will feed an Id dynamically to your ajax call as follows:
$(document).ready(function(){
$(document).on("click", '#next', function(event){
$.ajax({
url: buildurl(),
success: function(html){
$("#results").append(html);
$("#lastid").empty().load('html #start');
}
});
});
});
function buildurl()
{
return "load.php?start="+ $('#lastid').text();
}
This will force your event to always call this function and the function to get a fresh value from lastid.
Regards
you have to change your success function because you have multiple #lastid when clicking twice.
try something like:
success: function(html){
$("#lastid").removeAttr("id"); // remove's the id from #lastid
$("#results").append(html); // appends the new one
$("#lastid").empty().load('html #start');
}

Categories