Inject external javascript file in html body after page load - javascript

I want to load an external javascript after page is loaded. Actually the javascript contains source for an ad and its making page load slow. All I want is to delay loading & execution of ads to make sure fast page load.
thanks,
Bilal

You may just use this script at the last tag of your body block:
<script type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://yourdomian.com/your_script.js');
script.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(script);
</script>

var script=document.createElement('script');
script.type='text/javascript';
script.src=url;
$("body").append(script);
Courtsey

$("#selector").click(function(){
$.getScript("YourScript.js");
});
Then Run what is implemented in that script

I would look at using asynchronous Javascript loading. There are frameworks for this such as requireJS.

Without using something like jQuery getScript() and a promise or a proper loading library like requireJS, the script can be included in the page, but will load async so there's no guarantee it will be ready when you need it. If you're already using jQuery, the simple answer is then:
$.getScript( scriptUrl ).then( function() {
//do this ONLY after the script is fully loaded
});

Related

How can I call a library script after page is loaded?

I'm trying to call a library script (locomotive) in vanilla JS without Jquery, after the whole page and its assets had loaded. I've already tried with something like this:
<body onload="script('./js/lib/locomotive.min.js')";>
But it isn't working, the whole page loads but the script is never called. I've also tried placing the defer after the scripts call, but still nothing. I saw this other solution in other comments:
document.addEventListener("DOMContentLoaded", function(){
//....
// **But I don't know how to call in here the
*./js/lib/locomotive.min.js***
});
Is there something else I could try?
Your answer may be how to dynamic import script in js.
the base way is that insert a tag by dom api.
e.g.
const script = document.createElement('script')
script.src = './js/lib/locomotive.min.js'
document.head.appendChild(script)
if you wanna more functions, plz try loadjs

How can I make a Combine.js file load async

I have created a combined.js file page with all my inline and other scripts into one file...
How can I load these scripts asynchronously into my page? - I have done this because Google and Yahoo recommends this to speed-up my website loading.
I have already placed the file in my footer.php (I am using wordpress using wp_enqueue_script) but without async or defer tags, as it seem like I will have to hardcode these into my files?
In HTML5 you can use the 'async' attribute you can see here the support for it:
<script async src="myJavascript.js"></script>
The old way to do it, is like this:
<script>
var res = document.createElement('script');
res.src = "myJavascript.js";
var script = document.getElementsByTagName('script')[0];
script.parentNode.insertBefore(res, script);
</script>
This way has more support than you will ever need.

Adding external scripts in DOM from javascript code

I have included 3 external js files at the end of body.
Suppose my document already contains a js named as insertlibs.js and here is the code
var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script1);
// Similar way to include underscore
var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);
But what is happening sometimes, it is throwing an error that $ is not defined and I tried to debug in Firefox and there is a parallel download occurring for jquery and backbone and sometimes backbone library getting download earlier than jQuery which is causing this error.
As far as i know that if a script tag is included, it will block further request So as soon as I add jquery in dom. I am confused about the workflow here happening.
So i have found the solution, I merged both the js and making a single call which is working perfectly but that does not explain me the flow happening in above case. Please help.
This is because you are attempting to include backbone without ensuring that jquery has been completely loaded. To correct this, you can use the script's onload attribute to attach a callback which will be fired when jquery is loaded.
For ex:
var script1 = document.createElement('script');
script1.src='http://code.jquery.com/jquery-latest.js';
script1.type='text/javascript';
// add an onload handler
script1.onload = function() {
// load the rest of the scripts here
var script2 = document.createElement('script');
script2.src='hhttp://documentcloud.github.com/backbone/backbone-min.js';
script2.type='text/javascript';
document.getElementsByTagName('Body').item(0).appendChild(script2);
}
document.getElementsByTagName('Body').item(0).appendChild(script1);
As far as i know that if a script tag is included, it will block further request
No, the blocking / synchronous download is only when the tags are right in the parsed HTML (or are inserted via document.write during the parse); dynamically DOM-appended scripts load asynchronously and in parallel.
To do that but ensure that scripts are executed when their dependencies are met, you need to use AMD loaders.

Script not executing with a dynamically generated JQuery script tag

I have the following code in an external JS file (ie: test.js); which creates an additional script tag pointing to a JQuery source if it detects that a JQuery source isn't already there. The code actually creates the script tag and inserts it before the actual script that's doing the creating:
if (typeof(jQuery) == "undefined") {
var head = document.getElementsByTagName("head")[0];
// get any and all script tags
var scripts = document.getElementsByTagName("script");
// the actual script call the actions (ie: this one "test.js")
thisScript = scripts[scripts.length - 1];
// create element
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
head.insertBefore(script,thisScript);
}
The above works fine. However, the problem I'm having is that once the JQuery source script tag is created, the rest of the code on "test.js" doesn't work. It's as if the code can't access the JQuery functions (or doesn't know that JQuery is there).
Thus, the following code on "test.js" doesn't work:
$(document).ready(function() {
// ...
});
The error I'm getting according to FireBug with FF 12 is: "$ is not defined"
Any ideas as to why this is happening or how I can fix it?
NOTE: I know I can just place JQuery on target page; however, that isn't an option as
the code has to be able to detect if JQuery is there; and if not, then create the script tag pointing to JQuery and run the Jquery code.
When you insert a script tag manually like you are doing, that script is loaded asynchronously. That means that other parts of the page will NOT wait for that script to be loaded.
This is different than if the script tag is present in the source of the page because in that case, the script will load synchronously and other parts of the page will not execute until after that script is loaded.
The result of this is that the rest of your page javascript is executing BEFORE the dynamically inserted script tag has been loaded, parsed and run. Thus, you are trying to use jQuery before it's been installed.
I'm aware of two options for solving your issue:
Change the insertion of your jQuery script tag to something that loads synchronously. The only way I know of to do that is to use document.write() to write the new script tag to your document, not insert it into the head section like you're doing. Stuff that is added to the document with document.write() is processed synchronously.
Continue to insert your script dynamically like you are doing, but add a monitoring event so you will know when the script has been loaded successfully and only run your initialization code that uses jQuery AFTER you get that notification that jQuery has been successfully loaded.
There are also script loading libraries (such as require.js) that will do the second option for you.
It sounds like you are having an issue with load order. The '$ is not defined' error is triggered because jQuery is not yet loaded. Then you load jQuery. This of course does not reload your first script, so the error stands.
This has been answered here: Check if jQuery is included in Header (Joomla)
if (typeof jQuery == 'undefined') {
var head = document.getElementsByTagName("head")[0];
script = document.createElement('script');
script.id = 'jQuery';
script.type = 'text/javascript';
script.src = 'js/jquery.js';
head.appendChild(script);
}

Load js files after ajax inclusion

This is the deal, i'm importing some php files, one of the files has a slider, this slider requires .js files.
But when i make the ajax call, the file is imported but the js files aren't. Is this supposed to be like this?
I tried this:
var script = document.createElement('script');
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
window.onload=function(){
$(".cs_article").append('<p>Tdkasdlasdlkamsdklasmdasdaest</p>');
$.getScript('js/jquery.ennui.contentslider.js');
$.getScript('js/jquery.easing.1.3.js');
};
Kinda works, well, the append works on the DOM even with it being already loaded, but i can't get the scripts to run...
I've done my homework, searched on google, and found several ways of importing the scripts, but all end up with the same result...
this works
https://github.com/chriso/load.js
Bind your window.onload function to yourjQueryScriptTag.onload instead; before setting the src and appending it to the DOM, since onload may fire before jQuery is loaded.
http://jsfiddle.net/5SbXc/
Also, you may want to consider upgrading to a newer version of jQuery if possible.

Categories