Forum Moderators: open

Message Too Old, No Replies

Why can't I load a javascript in a div using ajax approach?

Trying to load large Javascripts through XMLHttpRequest

         

luckybuilding

10:18 pm on Mar 25, 2010 (gmt 0)

10+ Year Member




Hi all,
As large JavaScripts make webpages load heavily at the first load, I'm trying to load large Javascripts through XMLHttpRequest.
I try to ignore <script> tags in the upper parts of the page and then load the scripts in the bottom of the page.
I try to load the required scripts in the corresponding divs (some scripts should not load in the head)!
Therefor, I tried to solve the problem modifying a ajax script that loades the JavaScripts in the head section of the page!
But, it didn't work, when I modified it to load the new element in the div!
i.e.:



var newelement=document.createElement("<script type='text/javascript'>"+page_request.responseText+"</script>")
document.getElementById(containerid).appendChild(newelement)




I put all the samples I made to let you know what I exactly try to do:



Ajaxjsfetcher.js:



var ajaxjsfetcher={
loadingmessage: "<img src='loading.gif' /> Requesting content...",
exfilesadded: "",

connect:function(containerid, jsfiles){
for (var i=0; i<jsfiles.length; i++){
var page_request = false
var bustcacheparameter=""
if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE6 or below
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
var ajaxfriendlyurl=jsfiles[i].replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/")
page_request.onreadystatechange=function(){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
var newelement=document.createElement("<script type='text/javascript'>"+page_request.responseText+"</script>")
document.getElementById(containerid).appendChild(newelement)
}
}
document.getElementById(containerid).innerHTML=ajaxjsfetcher.loadingmessage //Display "fetching page message"
page_request.open('GET', ajaxfriendlyurl, true)
page_request.send(null)
}
},

load:function(containerid, jsfiles){
var jsfiles=(typeof jsfiles=="undefined" || jsfiles=="")? [] : jsfiles
this.connect(containerid, jsfiles)
}

} //End object



Sample html file to use it:



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="ajaxjsfetcher.js"></script>
</head>

<body>

<div id="ds">
TEST1

TEST2
<br/><br/><br/><br/><br/><br/><br/>

TEST3
</div>

<div class="moduletable" id="az_menu">

TEST4

</div>
<div id="sds">
TEST5

TEST6

<br/><br/><br/><br/><br/><br/><br/>
</div>
<script language="javascript" type="text/javascript">
ajaxjsfetcher.load("az_menu", ["az.js","RAz.js"])
</script>

TEST7

TEST8


</body>
</html>

daveVk

3:45 am on Mar 26, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



from [webmasterworld.com...]

var script = document.createelement('script');
script.type = 'text/javascript';
script.src = 'test.js';
document.getelementsByTagName('head')[0].appendChild(script);

May be easier way.

luckybuilding

9:05 am on Mar 26, 2010 (gmt 0)

10+ Year Member



daveVK:
Thanks! But, it makes the script to load at head & makes bad results! Because, the script makes some html output and I need to make it show in the corresponding div!
Using getelementsByTagName('head')[0] , it clears all the screen & shows the script result only!

daveVk

12:35 pm on Mar 26, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Assuming you can change the js, you could set a global variable to tell it where to put the html.

var script = document.createelement('script');
script.type = 'text/javascript';
script.src = 'test.js';
var testJsToDivId = 'az_menu';
document.getelementsByTagName('head')[0].appendChild(script);

luckybuilding

6:51 pm on Mar 26, 2010 (gmt 0)

10+ Year Member



Thanks man,
I would try to implement it in the script.
However, there is 3 scripts in the page that I'm trying to load them in such a way.
It may work in one of them. But, I don't know if I would be able to apply to all.

Isn't there any other approach to be able to apply it to all scripts universally?!

Fotiman

7:46 pm on Mar 26, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If you are trying to include a script which does document.write, which is what I think you mean when you say "the script makes some html output", you will not be able to use AJAX to pull it in.

document.write should be avoided because it is timing sensitive. If you call document.write after the page has finished loading (which may be the case if you use AJAX... you can't guarantee that it won't be), then it will replace the current document.

luckybuilding

10:38 pm on Mar 26, 2010 (gmt 0)

10+ Year Member



Hi Fotiman,
Thanks for your point. Yeah! As I checked, it was doing document,write & I changed them to document.getElementById(cid).innerHTML. It worked pretty well in the div! But, it resulted in some style damage in the parent page! It disabled (I think it "cleared") the "floating" parent divs! Any idea about it?!

As a whole case, do you agree with what I am doing in the page? (I mean using AJAX to load the huge scripts after the page loading to decrease the first loading time!)

daveVk

4:01 am on Mar 27, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I can not see why it should not work for as many scripts as you like, just name each global var, based on script name.

eg

var script = document.createelement('script');
script.type = 'text/javascript';
script.src = 'test1.js';
var test1JsToDivId = 'az_menu';
document.getelementsByTagName('head')[0].appendChild(script);

var script = document.createelement('script');
script.type = 'text/javascript';
script.src = 'test2.js';
var test2JsToDivId = 'az_body';
document.getelementsByTagName('head')[0].appendChild(script);

As Fotiman said don't use document write. InnerHtml should suffice.

As a whole case, do you agree with what I am doing in the page? (I mean using AJAX to load the huge scripts after the page loading to decrease the first loading time!)


If the scripts were not generating HTML I would agree, in this case it seems all the scripts need to be loaded before the page is readable ? so where is the advantage ?

luckybuilding

3:14 pm on Mar 27, 2010 (gmt 0)

10+ Year Member



daveVk:
The code you said works.
I don't know why, but it makes some changes in the style of the parent page! I use some floating DIVs in the page & it makes them to display incorrectly! The script only has some document.getElementById("az_menu").innerHTML codes that can not affect other things but it does! why could it be so?!

About advantage, the codes creates some unimportant menus in the page that would not affect all the page! But, they make the page to load heavily and the user needs to wait a lot of time for the first things to appear!
Using the approach may help me to show something to the visitor very fast not to let him abandon the page! Don't you think so?!

Fotiman

12:48 am on Mar 28, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Try using the Firebug plugin in Firefox and inspect the elements that are inserted, as well as the elements that are becoming incorrectly positioned. That might indicate what styles are being applied that are causing things to be misaligned.

daveVk

1:38 am on Mar 28, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The insertion of innerHTML may result in some resizing, leaving the floats out of position ? Putting a fixed size on az_menu may help.

The advantage, depends a lot on the particulars, it is probably worthwhile timing it both ways, and running YSlow or similar, download size/time may not be the critical factor. Getting something up quick is a good goal provided the visual effect of updating is considered.

tangor

5:24 am on Mar 28, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



user needs to wait a lot of time for the first things to appear

What is that time? Most days, even the most heavily laden pages load quickly enough to not lose visitors (broadband/adsl). It is images that slow things down.

luckybuilding

5:18 pm on Mar 28, 2010 (gmt 0)

10+ Year Member



Fotiman and daveVK:
Thanks for your helps. I would work on it. I usually use IE8's developer tool that showed everything are loaded as usual! But, I would check the Firebug & YSlow too!

Tangor:

There still is dial-up users or who has a low speed internet access in the world! And, as I checked through my site feedbacks! There are many!
Also, the broadband users (as my experience show) are addicted to the speed! So, they would abandon websites that are loading slowly!