Load js files after ajax inclusion - javascript

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.

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

Dynamically load javascript files and make sure they are cached

I want to load my javascript files after the page is loaded and make sure that they are being cached.
This question has been asked and answered a lot but they all suggest loading it with jQuery ($.getScript) while one of the files I want to load is the jQuery itself and I can not use jQuery. there are some options like:
(function(){
var newscript = document.createElement('script');
newscript.type = 'text/javascript';
newscript.async = false; //as I'm going to execute some functions
//after this I want to make sure that the
//script is fully loaded
newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';
(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);
})();
but I'm not sure if they are cached or not.
and Is there a way to fire an event when dynamically loading script is done?
You can easily check if they are cached by loading your page for a second time with the network tab of the developer tools of your browser opened. You can tell by the way the scripts are loaded whether the file is cached or not.
They should be, by the way. You're basically inserting a script tag through JavaScript, after which the script is loaded as it would be if the tag was already in the page.
If you make it load asynchronously, you can attach an onload event to a script tag, which will fire as soon as the script is loaded. This should work in any modern browser, including IE9+ in standard mode. If you need support for IE8, you will have to do some extra work, which is what $.getScript() also does. An in-depth discussion of that jQuery functionality, with alternative code snippets can be found in the question 'onload' handler for script tag in Internet Explorer.

Delay function call when dynamically loading javascript files

I am using enquire to dynamically load javascript files but hitting what I can only assume to be a loading priority problem since it works some of the time. Is there a way to hold off running a function until all files are loaded?
The relevent bit of enquire is
enquire.register("screen and (min-width: 564px)", {
match : function() {
loadJS('script/jquery.js');
loadJS('script/jquery.slides.min.js');
loadJS('script/TMSScript.js');
}
and the load function is
function loadJS(url)
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}
The function I need to run is located at the end of TMSScript.js and it calls the jquery plugin so all 3 files need to be loaded in order for it to work. If I load all files in the header then the function will execute fine with a simple onload call in the body.
The idea is that a different method will be used on mobiles for my gallery (probably jquery mobile) and I don't want to load any unnecessary files.
Someone may correct me, but I believe outside of either loading these three in separate script tags placed in the correct order, or loading a single js file with these plugins concatenated in the correct order, you can't. Loading a src on a programatically created element now runs in an async fashion (in current browsers anyways I beleive), meaning you wouldn't be sure exactly when it's going to return back, and in what order.
It sounds like you want to use something like browserify or require.js which can help handle what you're trying to accomplish. I suggest checking out those projects.

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.

javascript dynamic script creation vs script defer

I was reading up on non blocking ways of loading javascript.I came upon some interesting concepts, especially a new one to me. The script defer attribute.
I know about dynamically creating scripts and inserting them to the head of the document, which i have a function for.
for example:
function loadJS(loc){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = loc
}
I have seen this defer attribute and Im not sure on how to use it and what its main advantages/disadvantages are?
Thanks in advance guys!
I've been looking for similar answers and was about to post a question when I found this stackoverflow question -- and yours.
So here is what I've found out:
The script defer approach hints to a browser to wait until the document has finished loading before executing the script. BUT it still loads the script first (assuming that they're located in the HEAD of the document).
jQuery has a .getScript() method which can be used to load any number of scripts whenever and wherever needed. You could even apply it to an onClick event on a link for instance!
There are also several libraries aimed at dynamic, non-blocking loading such as LABjs, RequireJS or HEADjs.
I guess it's up to you which approach you choose, if you're only on a small project and are already using and/or used to using jQuery then I'd go with that. Otherwise maybe check out one of the libraries.
Just to state again however that as best as I can tell DEFER will not prevent page blocking when loading scripts. But a typical and very simple solution to this is to include all your scripts in the page footer rather than the HEAD.
People please feel free to correct me if I'm wrong on any of the above! -- Thanks

Categories