Dynamic loading of JavaScript file not working as expected - javascript

I am loading javascript file dynamically to speed up performance of my page. The code is
<head>
<script type="text/javascript">
function includeJS(){
var scriptElement = document.createElement('script');
scriptElement.type = "text/javascript";
scriptElement.src = "script/TestScript.js";
document.getElementsByTagName('head')[0].appendChild(scriptElement);
testFunction();
}
</script>
</head>
The testFunction() is present inside the TestScript.js. So it is throwing an error like 'testFunction() is undefined' as the JavaScript file is not completely loaded. So I tried with setTimeout function to fix it. The code is
setTimeOut('testFunction()',1000);
Its working fine now. But I can not put the delay time 1000 in server as the JavaScript file loading is depends on the internet speed and file size. So is there any other way to fix it.

Related

Refresh div content which contains a script that gets the feed as document.write

I have been trying to do webpage which shows me all kinds of stuff that I use daily. I tried to get a Reddit feed there, which would refresh automatically every x seconds (60 sec or something). But the problem is that the feed comes as
document.write({INSERT FEED HERE});
which is loaded asynchronously and so it gives an error:
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
So is there any way to get this updating by itself, without updating the whole page.
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="reddit">
<script>
$(document).ready(
function() {
setInterval(function() {
reload_js();
}, 60000);
});
function reload_js() {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://www.reddit.com/r/ProgrammerHumor/new/.embed?limit=10&t=all";
document.getElementById("reddit").appendChild(s);
}
</script>
</div>
</body>
This is the simple page I have right now for the reddit feed.
By default, the .embed webservice use document.write if no callback parameter is defined.
Just add a callback parameter, like this
https://www.reddit.com/r/ProgrammerHumor/new/.embed?limit=10&t=all&callback=yourFunction
And add a yourFunction function that will append the content
function yourFunction(data) {
document.getElementById("reddit").appendChild(data);
}
Enjoy :)

Load javascript source not working

Hello i need to use JavaScript to load a script tag in the head of my document. The problem is i create the script element fine, but this source is not loaded once the rest of the javascript executes. Is there a better way to load the script before the rest of the JS executes?
<script>
var jQ = document.createElement('script');
jQ.src = '../EmergencyBroadcastScripts/source/jquery-1.10.1.min.js';
jQ.type = 'text/javascript';
document.head.appendChild(jQ);
$.noConflict();
jQuery(document).ready(function () {
jQuery('.fancybox').fancybox();
});
</script>
This code will produce the error "$.noConflict is not a function" because its not loading the JQ script source before it executes my code. This is my problem. Any ideas??
Try:
jQ.onload = function () {
$.noConflict();
jQuery(document).ready(function () {
jQuery('.fancybox').fancybox();
});
}
I don't know if it will work in this scenario but it works with images on a canvas.

Place 'script' before the end of BODY tags with jQuery

This is the 'script' I want before the 'body' tag:
<script type="text/javascript">
var vglnk = { api_url: '//api.viglink.com/api',
key: '89dcd0a12ff35d227eaaaff82503030b' };
(function(d, t) {
var s = d.createElement(t); s.type = 'text/javascript'; s.async = true;
s.src = ('https:' == document.location.protocol ? vglnk.api_url :
'//cdn.viglink.com/api') + '/vglnk.js';
var r = d.getElementsByTagName(t)[0]; r.parentNode.insertBefore(s, r);
}(document, 'script'));
</script>
I want this code to be where I've put "HERE"
<html>
<head>
</head>
<body>
Some HTML and stuff
HERE
</body>
</html>
How would I go about this in jQuery?
(I'm doing this from an extension. Mainly in Chrome, but also Firefox and Internet Explorer.)
You need the content script to do the insert on every page you want.
The code of the content script is really simple and doesn't need jQuery.
var code = "your script code here";
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.appendChild(document.createTextNode(code));
document.body.appendChild(script);
As it will only be called once you don't even need to define a function. You can debug the code using debugger on any web the content script is attaching (F12) you will see your code in the content script tab.
I had the same issue regarding the best place to add jQuery: to the header or before the body tag? The answer is that it does not matter.
The whole page (or DOM) needs to initialize or load in order to accomplish what you are doing.
And...
The more information within the body, the more reliance you need to make sure the document is loaded.
The two sentences above are redundant because:
All jQuery UI, basic syntax, widgets, etc. are triggered with:
$(document).ready( function() {
$("#some_id").click( function {
More code here
});
});`
The code above means that the the full HTML page (or 'document') needs to be loaded before jQuery can run, AKA initialized.
There is an order that jQuery needs to be loaded for a UI to work. The actual library needs to be first, then the UI. The library can be downloaded from jquery.com and uploaded to the designers web space or through a CDN (content display network) to save on bandwidth. Here is an example of how the order should be:
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script>
Notice the library is the first line, and then the UI. In this case I loaded jQuery Mobile.
In conclusion, it does not matter. It is a preference mostly. More in on Unclear where $(document).ready goes.

Difference between calling a script in the onload event or placing code at end of html

I was reading the google maps api documentation and stumbled across a paragraph that explains the Asynchronously Loading the API. The api documentation can be found here
As an example it showed a script that looks like this:
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
What is the difference between this piece of code and just simply adding the script call all the way to the end of the html markup? Like this:
<!-- rest of the markup -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=TRUE_OR_FALSE&callback=initialize"></script>
</body>
</html>
You usually want your JS scripts to run after the DOM is loaded and this event doesn't necessarily occur when your html is read/parsed. I.E. There exists some time between reading the HTML and building the DOM that your JS needs to traverse.

Running a Javascript file (Adsense) after page load

I'm trying to run Adsense after the page has loaded. But inserting the Adsense script file into an element doesn't seem to run it. Here is the version without window.onload (I modeled it after the Analytics script):
<script type="text/javascript">
// adsense variables
google_ad_client = "my-pubid";
google_ad_slot = "my-adslot";
google_ad_width = 728;
google_ad_height = 90;
(function() {
var ad = document.createElement('script');
ad.async = true;
ad.src = 'http://pagead2.googlesyndication.com/pagead/show_ads.js';
var s = document.getElementById('ad_top');
s.appendChild(ad);
})();
</script>
The onload version is the same, just wrapped in window.onload. Checking Chrome dev tools, the script is inserted in the #ad_top div but no ads show. I've tried moving the variables to the very top of the page and it still doesn't display even though the script is inserted fine.
Note: I'm not interested in loading it inline at the bottom of the page and moving it (as in an answer to a related question), I don't want to start loading anything until after the page has fully loaded.

Categories