Is dynamic script injection in html blocking? - javascript

In this question it is clearly shown how to programmatically inject a new script in an HTML page.
What I'd like to ask, however, is if such injection is blocking, that is, it'll wait for the injected script to be loaded and executed before calling the next line.
For example
function inject(script_url) { ... }
// somewhere in the code
inject('/path/to/script.js');
func_in_script(); // <-- will "func_in_script" be defined at this point?
EDIT:
This is what I found out trying:
If I use native JS like
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false; // !!!
script.defer = false; // !!!
document.head.appendChild(script);
Then the functions in the loaded script are not immediately available after the call to appendChild(); however if I use jQuery like:
$('<script/>', {
type: 'text/javascript',
src: url,
async: false,
defer: false
}).appendTo('head');
It works as I'd like it to.

Related

The page failed to load my scripts module after finishing to load

I create the script tag and append it on the document with the event of loading so that the page when finishes to load it will execute my script but i'm i'm facing with the problem where the page didn't load my script and didn't drop the error to my scripts code looks like this
window.addEventListener('load',() => {
script = document.createElement('script');
script.type = 'module';
script.src = 'custom.js';
document.body.appendChild(script);
});
but i doesn't work for me
check up if you are doing this over local host connection because the module didn't run without the connection or you the problem might be in your browse if you are using IE 7 or earlier but the solution of the IE 7 or earlier is this
if (window.addEventListener) {
window.onload = scriptFunction();
} else if (window.attachEvent){
window.onload = scriptFunction();
}
function scriptFunction() {
script = document.createElement('script');
script.type = 'module';
script.src = 'custom.js';
document.body.appendChild(script);
}

jQuery $.getScript does not work half of the time

I am using jQuery to load a script from Mapquest within the cordova onDeviceReady function. However, half the time the script does not load properly and the functions cannot be used.
$.ajax({
url: "http://www.mapquestapi.com/sdk/leaflet/v2.s/mq-geocoding.js?key=sv99PLA3H8jGWSa1a097UKewBWrNWLWN",
dataType: 'script',
success: function(){alert('hello')},
async: false
});
Is there anything that I can change to ensure that the script is always loaded properly? The script is always able to alert('hello'), but even then, the functions will not always work properly.
You can load the script dynamically without the $.getScript function as the following does:
function loadScript ( src, callback )
{
var script = document.createElement ( 'script' );
script.type = 'text/javascript';
script.async = true;
script.onerror = function ( err )
{
throw new URIError('The script ' + err.target.src + ' is not accessible.');
}
if(callback && typeof callback == 'function')
script.onload = callback;
document.head.appendChild(script);
script.src = src;
}
What it does is:
Creates a <script> element;
Tells the browser that it should be loaded asynchronously so it doesn't interrupts the rest of the resources while they load;
Uses the onerror and onload events to provide feedback on the script loading;
Appends the script to the <head> and sets the src making it actually load.
In your case, you'd use it like this:
loadScript ( "http://www.mapquestapi.com/sdk/leaflet/v2.s/mq-geocoding.js?key=sv99PLA3H8jGWSa1a097UKewBWrNWLWN", function ( )
{
alert(1);
} );
Compatibility
Keep in mind that the async attribute does not works on all browsers: http://caniuse.com/#feat=script-async

how to know if the javascript, which has been loaded by a javascript, has been loaded [duplicate]

This question already has answers here:
'onload' handler for 'script' tag in internet explorer
(2 answers)
Closed 7 years ago.
I know my subject is quite tricky but i dont know how to much more ellaborate it on the subject alone.
so here how it goes.
i have a button
Load IT!
on the script tag:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
alert("done! the file has been loaded");
}
the script well, when loaded will automatically have a modal box.
but the problem is, my alert seems to fire first than what is one the script
so how will i know if i have finished to load the script?
update for the first attempt to answer:
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','http://www.thisismyexternalloadingjsfile"');
$('body').append(script);
$(document).ready(function() {
alert("done! the file has been loaded")};
}
same problem
alert does indeed run before the script has been loaded. All that appending the script tag to the page does is append the script tag to the page. Then the browser has to download the script and, once received, run it. That will be after your loadTheFile function has exited.
So you need to get a callback when the script has actually be loaded and run. This is more standard than it used to be, but still has some cross-browser hassles. Fortunately for you, jQuery's already solved this problem for you (since you're using jQuery already):
function loadTheFile() {
$.getScript('http://www.thisismyexternalloadingjsfile"')
.then(function() {
alert("done! the file has been loaded");
});
}
Re your comment:
but my script file has data-* attributes
Assuming you're talking about data-* attributes on the script tag, then you'll have to do a bit more work, but it's still fairly straightfoward:
function loadTheFile() {
var load = $.Deferred();
var script = document.createElement('script');
script.src = 'http://www.thisismyexternalloadingjsfile"';
// No need for `type`, JavaScript is the default
script.setAttribute("data-foo", "bar");
script.onreadystatechange = function() {
if (script.readyState === "loaded") {
load.resolve();
}
};
script.onload = function() {
load.resolve();
};
load.then(function() {
alert("done! the file has been loaded");
});
document.body.appendChild(script); ;// Or wherever you want to put it
}
The onreadystatechange bit is to handle older versions of IE.
Rather than forge the script with text and jQuery, just use native Javascript:
var s = document.createElement('script');
s.onload = scriptLoaded;
s.src = '/path/to/my.js';
document.body.appendChild(s);
function scriptLoaded() {
console.log('Script is loaded');
}
Try something along these lines:
Your main page:
function whenScriptIsReady(){
alert('This function is called when the other script is loaded in!')
}
function loadTheFile() {
var script = $("<script><\/script>");
script.attr("type", "text/javascript");
script.attr('src','myotherjs.js');
$('body').append(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Load IT!
myotherjs.js:
alert('This will automatically run when the JS is loaded in!');
whenScriptIsReady();
JavaScript is executed asynchronously, so you alert will be executed before the browser can load the new script. If you want to execute logic after the script has been loaded, you could add an event listener to your script that will call the function 'loadFunc` once the script load is completed:
var loadFunc = function() {
alert("External Javascript File has been loaded");
};
//Other browsers trigger this one
if (script.addEventListener)
script.addEventListener('load', loadFunc, false);

How to conditionally include assets in the <head> with Angular

I am building a one-page Angular app. One of the views has content which depends on an external javascript library.
I don't want to include this external JS resource on every view of the site, just the single view which depends on it.
What is the best way to conditionally include blocks of code based on the current view?
If it's possible I'm hoping I can place in the something like this:
<script ng-if="view == 'view1'" type='text/javascript' src='http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js'></script>
So you should include the library script in page.
Then within directive bound to elements it needs to act on do the initialization.
app.directive('unity', function () {
return {
link: function (scope, element, attrs) {
// element is jQuery object when jQuery.js is included in page
// before angular - or it is a jQLite object similar to a jQuery object
// config code
u.initPlugin(element[0], "web_ovar_beta.unity3d");
}
}
});
Usage in view:
<div unity></div>
This can easily be expanded to pass in attributes to the directive from controller
It is
<script ng-if="view == 'view1'" type='text/javascript' ng-src='http://webplayer.unity3d.com/download_webplayer-3.x/3.0/uo/UnityObject2.js'></script>
And it is something that you don't want to do. It doesn't guarantee that the script won't be loaded twice. Since the script is being used for particular view, make it one-time resolving service
app.factory('unityResolver', function ($document, $rootScope, $q, $timeout) {
var deferred = $q.defer();
var script = angular.element('<script>')[0];
script.src = '...';
script.async = true;
script.onload = script.onreadystatechange = function () {
if (['loaded', 'complete', undefined].indexOf(script.readyState) < 0)
return;
script.onload = script.onreadystatechange = null;
deferred.resolve();
$rootScope.$apply();
}
script.onerror = function onerror() {
script.onerror = null;
deferred.reject();
$rootScope.$apply();
};
$timeout(onerror, 20000);
$document.find('head').append(script);
return deferred.promise;
});
and use it in view/route resolve.
What your wanting to in turn is impossible.
You can get Javascript to include a javascript file if you want however if your using AJAX to load the content that is needed leave it in there it would be the same amount of time to load anyway. but once a file has been loaded into JavaScript it finished with you can remove the file from your HTML but the JavaScript engine still has the content of that file loaded in to it.
Try it in your browsers(chrome or FF with Firebug) inspector now:
open a new tab and go to about:blank then put the code below into the console
var include = (function(){
// the reference to the script
var theScript;
return function (filename, status){
if(status == 'on'){
// adding a script tag
var head = document.getElementsByTagName('head')[0];
theScript= document.createElement('script');
theScript.src = filename;
theScript.type = "text/javascript";
head.appendChild( theScript )
}else{
// removing it again
theScript.parentNode.removeChild( theScript );
}
}
})();
taken from Remove specific <script> tag in <head> tag by onclick event
then in your inspector's console
include("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", 'on')
now check Elements and you will see jQuery loaded in the pages head tag.
and type jQueryinto console and you will see function (a,b){return new n.fn.init(a,b)}
And then use this into your console
include("https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js", 'off')
and check your elements tab again the script tag will have gone.
however go back to console and type jQuery again and you will see function (a,b){return new n.fn.init(a,b)} as even though you have unloaded the file you can't remove the executed code from memory.
You have 2 options another framework page gets loaded into an iFrame or if you want to use Anagular to load the View in then just include the file in your head there is no point not having and then removing it as once it is loaded it's loaded

JavaScript dynamic loading

I have senerio, where I need to render my HTML page by using dynamic JavaScript.
I am using loadScript function to load external JavaScript and passing callback funtion. In my HTML page , I am loading this script for my header.
My header section is working perfectly after the script is loaded and I my head section I can see my new script.
However , when I am trying to use the variables from this script its undefined.
function loadScript(url,callback){
var script = document.createElement("script");
script.type = "text/javascript";
script.id="acvDataRequest";
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
alert(dataHeader) // I CAN SEE MY OBJECT FROM LOADED SCRIPT
callback();
};
}
script.src = url;
alert(dataHeader); // IT SAYS UNDEFINED
}
calling a script using :
var actionName ="JSONdata/json.js";
loadScript(actionName,mergeTemplateJSONScript);
Please advice , why i can't see my variables even if my script is there.
Inside script.onload , I am able to see my variable but not outside
The line script.src = url; triggers the loading of the script file. If you call alert immediately after it your external script has not been loaded yet. You can only access variables from the json once the onreadystatechange or onload functions have been called.
What you should do is using it like this:
var actionName ="JSONdata/json.js";
loadScript(actionName,function(){
alert(dataHeader);
});
What you assign:
script.src = url;
that just starts the loading of the dynamic script. When you call the second alert() on the very next line your script has not yet loaded (it is loading in the background at that point). You can only reliably access the variables from the newly loaded script from within the onload handler or in some function called from the onload handler.
Keep in mind that the dynamic loading of scripts is asynchronous. That means it happens in the background while other scripts keep running (thus your second alert() runs before the script has finished). And, then the script finishes loading some time later and when it does the onload handler is called.
So, when you dynamically load scripts, all code that uses those scripts needs to either be in the onload handler, in some function called from the onload handler or guarenteed not to execute until some time later (such as in an event handler that you're sure won't happen before the script finishes loading).
To explain further, I've added some annotations to your code:
function loadScript(url,callback){
var script = document.createElement("script");
script.type = "text/javascript";
script.id="acvDataRequest";
document.getElementsByTagName("head")[0].appendChild(script);
if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function(){
// ** your script is now loaded here **
alert(dataHeader) // I CAN SEE MY OBJECT FROM LOADED SCRIPT
callback();
};
}
script.src = url;
// ** your script is in the process of loading here and has likely not completed **
alert(dataHeader); // IT SAYS UNDEFINED
}

Categories

Resources